1

I am trying to validate a username field. The field must have numbers, letters and no special chars.

This pattern="[A-Za-z0-9]" stands for username with numbers and letters.

What the pattern should be?

4 Answers4

1

Your pattern stands for a single uppercase-char, lowercase-char or number.

The pattern you want looks like this:

/^[a-z\d]+$/i

Explained:

  • ^ - from the start of the string (or line with the m flag)
  • [ - start character class
  • a-z - range of characters from a to z
  • \d - the same as 0-9 (any digit)
  • ] - close character class
  • + one or more
  • $ - end of string (or line with the m flag)

Then we have the flags outside the actual regexp // itself. We're using the i flag which stands for case insensitive.

Cheatsheets / Tools

SidOfc
  • 4,552
  • 3
  • 27
  • 50
1

try this

<input type="text" class="form-control" name="username" onkeyup="if (/[^|a-z0-9]+/g.test(this.value)) this.value = this.value.replace(/[^|a-z0-9]+/g,'')">
Abdulmajeed
  • 552
  • 7
  • 8
0

I don't know if this can be done in raw HTML (doubt it), so you'll need some javascript. You can have a function called on the "onchange" attribute if you like, so the element would be like:

<input id="username" type="text" onchange="validate()" name="name" value=""/>

The javascript function would then just access the element, get the value, and check what is in it, like so:

function validate() {
     var name = document.getElementById("username").value;
     //do checking here however you like (regex, iteration, etc.)
}

BUT, this needs to be done server side. You can do it client-side if you really want to, but it MUST be done on the server side, in any case. I assume you meant on the client side since you tagged the question with HTML, rather than a server side language.

Padge
  • 81
  • 6
0

This should work to test a string for only characters and numbers with javascript.

/^[a-zA-Z0-9]+$/
Jason Palmer
  • 99
  • 2
  • 8