1

i am doing client side validation in Zend framework2 and using regex. test class for this purpose but not getting the correct result i m using in the following way

var regex = new RegExp('/^[a-zA-Z0-9_-\s]{1,50}+$/');
console.log(regex.test(id_val));

but it always returns false. does any one knows how to use it?

2
  • The syntax looks fine. What's the value of id_val? Add that to the question. Commented Sep 30, 2013 at 12:45
  • 2
    Creating a RegExp object using new does not take delimiters, and two quantifiers after another are also an error. (Your browser’s JS console should have told you about the latter already.) Commented Sep 30, 2013 at 12:48

1 Answer 1

1

Remove surrounding / from the string literal, and trailing +. Also escape \ as commented by @Bergi.

var regex = new RegExp('^[a-zA-Z0-9_-\\s]{1,50}$');
regex.test('1'); // => true

Or, use the regular expression literal:

/^[a-zA-Z0-9_-\s]{1,50}$/.test('1'); // => true

Use regular expression literal unless you need to generate regular expression runtime.

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

2 Comments

…and escape the backslash. No, just use the literal instead of the constructor.
still i m confused that how to enclosed regex in quotes as it is coming in the form of string form another page.

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.