0

I want to validate a string in JavaScript to allow alphanumerics, "(", ")" , and spaces. So test strings are:

s1 = "This $h00l*&^ not w0rk342*_(&, <and> always fail" 
s2 = "This should work (ABC1234)"

my code:

var regX = new RegExp(/A-Za-z0-9\\(\\)\\x20+/);
if(!regX.test(s1)){
    alert("InValid value.");
}

But it fails for both the strings.

Also as test() function evaluates the matches in the string and not the whole string https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

Can someone please help. Thanks in advance

1
  • As written, your RE will just match strings containing "A-Za-z0-9() +" Commented Feb 6, 2014 at 17:21

1 Answer 1

3

You should use this regex:

/^[A-Za-z0-9() ]*$/

Replace * with + if you don't want to allow empty string.

^ and $ test for beginning and the end of the string respectively.

* means repeat 0 or more times. + means repeat once or more.

To specify a character class (i.e. a set of character), you need to place the characters inside [].


To further shorten the regex:

/^[a-z\d() ]*$/i

i flag will make the regex matches case-insensitively, which remove the needs to specify A-Z.

\d is the shorthand character class for digits 0-9. Shorthand character class can also be included inside character class.

Sign up to request clarification or add additional context in comments.

1 Comment

You could shorten it by using the i flag and removing the A-Z option, as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.