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 ]/))
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 ]/))
Share
Improve this question
asked May 26, 2016 at 10:40
Jim PeetersJim Peeters
2,88310 gold badges35 silver badges55 bronze badges
3
-
1
anchors
name.match(/^[a-zA-Z1-9 ]+$/)
– anubhava Commented May 26, 2016 at 10:40 -
1
last character i.e.
a
is matched..see here..do what @anubhava says – rock321987 Commented May 26, 2016 at 10:41 - As an addition: you can check your regular expressions using this online tool: regex101. – Rhapsody Commented May 27, 2016 at 12:29
4 Answers
Reset to default 6You 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
.
It returns true because the last character ('a') is ok. Your regex doesn't check whether the plete input matches the regex.
Try this one: ^[a-zA-Z1-9 ]*$
if(!/[^a-zA-Z0-9]/.test(name)) {
// "your validation message"
}
try this
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!!');
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744225823a4563999.html
评论列表(0条)