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?
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?
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 classa-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
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,'')">
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.
This should work to test a string for only characters and numbers with javascript.
/^[a-zA-Z0-9]+$/