RegExp.Test always returns false

I have the following code in JSfiddle:

http://jsfiddle.net/ACG2D/

$(document).ready(function() { $('.testThis').click(function() { $('.regexValidation').each(function() { if ($(this).val() != "" || $(this).val() != null) { // Check the regex var expression = new RegExp('/^[0-9a-z_]+$/i'); var myVal = $(this).val(); if (expression.test(myVal) == true) { // All is okay alert("OK"); } else { alert("Error"); } } }); }); }); 

The intended plan is only to skip alphanumeric and underscores. Ban spaces and punctuation, etc.

I cannot understand why this is happening incorrectly, but always returns false for the test.

+4
source share
4 answers

Your syntax is incorrect.

Change it to var expression = /^[0-9a-z_]+$/i;

Unlike PHP, Javascript supports regular expression literals. The syntax /.../ creates a RegExp object.

The RegExp constructor accepts a regular expression as a string without delimiters.
Therefore, you can also write new RegExp('^[0-9a-z_]+$', 'i')

+8
source

Remove quotes from RegExp:

 var expression = new RegExp(/^[0-9a-z_]+$/i); 
+4
source

Take out the quotes as follows: new RegExp(/^[0-9a-z_]+$/i);

+1
source

use the slash "/" instead of quotes at the beginning and end of the regular expression.

for your code, it should be like this:

var expression = new RegExp('/^[0-9a-z_]+$/i');

0
source

All Articles