Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression always returns true

I have following regular expression in JQuery. It always returns true.

var reg = new RegExp("[a-zA-Z0-9 ,]+");
var key = $('#keyId').val().trim();
if (key.match(reg)) {
  $("#TitleError").hide();
}
else {
  $("#TitleError").text("special characters not allowed!!").show();

}

It returns true for everything, for example "ABCD, ^&&&^&" should be false, it returns true.

like image 407
TBA Avatar asked Jul 16 '13 06:07

TBA


People also ask

Does regex return true or false?

JavaScript RegExp test()If it finds a match, it returns true, otherwise it returns false.

What do regular expressions return?

Regular expressions are used with the RegExp methods test() and exec() and with the String methods match() , replace() , search() , and split() . Executes a search for a match in a string. It returns an array of information or null on a mismatch. Tests for a match in a string.

Does re match return true?

But to elaborate, re. match() will return either None , which evaluates to False , or a match object, which will always be True as he said. Only if you want information about the part(s) that matched your regular expression do you need to check out the contents of the match object.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


2 Answers

match returns the matches found in the string. what you really want is test eg. like this

/^[a-zA-Z0-9 ,]+$/.test(key)
or 
reg.test(key)
like image 128
shyam Avatar answered Oct 22 '22 17:10

shyam


You regexp should be:

var reg = new RegExp('^[a-zA-Z0-9 ,]+$');

like image 38
Arkadiusz 'flies' Rzadkowolski Avatar answered Oct 22 '22 16:10

Arkadiusz 'flies' Rzadkowolski