admin管理员组文章数量:1401176
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!!');
}
版权声明:本文标题:regex - Why is this regular expression in javascript still allowing special characters [a-zA-Z1-9 ]? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744225823a2596083.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论