regex - Why is this regular expression in javascript still allowing special characters [a-zA-Z1-9 ]? - Stack Overflow

I don't want to allow special characters but this regular expression still allows them, what am I

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
Add a ment  | 

4 Answers 4

Reset to default 6

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.

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信