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
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!!');
}

本文标签: regexWhy is this regular expression in javascript still allowing special characters azAZ19 Stack Overflow