Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  85] [ 4]  / answers: 1 / hits: 19540  / 10 Years ago, wed, august 27, 2014, 12:00:00

I am getting regex string from json object (yes its dynamic and will be always be string) i want to test this with textbox value.



But even if i pass valid input text it does not pass regex condition



code :



var pattern = /^[A-Za-zs]+$/;
var str = Some Name;
pattern = new RegExp(pattern);
if(pattern.test(str))
{
alert('valid');
}
else
{
alert('invalid');
}


Fiddle :- http://jsfiddle.net/wn9scv3m/


More From » regex

 Answers
17

Two problems:




  • You need to escape the backslash.

  • You need to remove the forward slashes on the beginning and end of string.



Corrected code:



var pattern = ^[A-Za-z\s]+$;
var str = Some Name;
pattern = new RegExp(pattern);
if(pattern.test(str))
{
alert('valid');
}
else
{
alert('invalid');
}


http://jsfiddle.net/wn9scv3m/3/


[#69642] Monday, August 25, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
robinh

Total Points: 371
Total Questions: 105
Total Answers: 89

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
;