Using javascript regular expressions to stop users from entering non-aphanumeric characters or white spaces
Say you want to stop users from entering non-aphanumeric characters or white spaces.
Using regular expressions would be the easiest method:
Here is my javascript code:
<script language="Javascript">
function alphaNumericCheck(){
var regex=/^[0-9A-Za-z]+$/; //^[a-zA-z]+$/
if(regex.test(document.add_data.password.value)){
alert("Good")
return true;
} else {
alert("Please fix: password")
return false;
}
}
</script>
For numbers only use /^[0-9]+$/
For mixed text and numbers, with spaces /^[0-9a-zA-Zs]+$/
Here are more useful regular expressions:
[a-zA-Z] any letter
d any number; same as [0-9]
D any NOT number; same as [^0-9]
w any alphanumeric character; same as [a-zA-Z-0-9_]
W any NON-alphanumeric character; same as [^a-zA-Z0-9_]
s any whitespace (tab, space, newline, etc...)
S any NON-whitespace
n newline
t tab
To view a full html sample of the above code click the links below using regular expressions in JavaScript


(16 votes, average: 4.25 out of 5)
“For mixed text and numbers, with spaces /^[0-9a-zA-Zs]+$/”
This does not work !
Here is the correct one :
/^[0-9a-zA-Z\s]+$/”
BTW, thanks for your article that saved us bunch of hours !
Pingback: Javascrit Remove Non-Alphanumeric Characters - Good quality PHP, ASP.NET, Ajax and JavaScript script collection and resource blog.
Since it is regex, wont /\W/ work just as well?
Thanx for your article!!
This was very much helpful and deftly saved our lot of time..
Very helpful, thanks. Though restricting character input for passwords is a little silly, and rather insecure.
/\W/ is a nice shortcut, but it excludes the space.
I used this for alphanumeric and space input only.
EXAMPLE
function checkAlphanumeric(v) {
var regex=/^[0-9a-zA-Zs' ']+$/; //^[a-zA-z' ']+$/
if(regex.test(v.value)){
return true;
} else {
alert(lng.js_req_alphanumeric)
return false;
}
}
And for the form input onKeyUp=”return checkAlphanumeric(this)”
EXAMPLE:
In Advance Thanks.The following code works for me with out accepting the wild cards in middle of the string:)
123!! #%>>23d test
does not support internationalization!
I’ve been exploring for a little bit for any high-quality articles or blog posts in this kind of house . Exploring in Yahoo I finally stumbled upon this website. Reading this information So i am glad to show that I have a very just right uncanny feeling I found out exactly what I needed. I so much certainly will make certain to don?t disregard this web site and give it a glance on a constant basis.