Reputation: 2863
I don't want to allow special characters but this regular expression still allows them, what am I doing wrong?
When i type for name : '&é"é&'é"&'&é"'a' It still gives back 'true'
name.match(/[a-zA-Z1-9 ]/))
Upvotes: 3
Views: 1065
Reputation: 2111
if(!/[^a-zA-Z0-9]/.test(name)) {
// "your validation message"
}
try this
Upvotes: 2
Reputation: 1527
This will work for you:
var nameregex = /^([A-Za-z0-9 ]$)/;
var name = document.getElementById('name').value;
if (!name.match(nameregex)) {
alert('Enter Valid Name!!');
}
Upvotes: 1
Reputation: 6077
It returns true because the last character ('a') is ok. Your regex doesn't check whether the complete input matches the regex.
Try this one: ^[a-zA-Z1-9 ]*$
Upvotes: 3
Reputation: 87203
You need to use RegExp#test
with anchors ^
and $
.
/^[a-zA-Z1-9 ]+$/.test(name)
String#match
return an array if match is found. In your case, a
at the end of the string is found and array is returned. And array is truthy in the Javascript. I believe, the array is converted to Boolean, so it returned true
.
Upvotes: 6