Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegExp.Test always returning false

I have the following code at 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 to only let alphanumeric and underscores through. Disallowing spaces and punctuation etc.

I can't figure out why this is going wrong, but it always returns false for the test.

like image 755
Dave Avatar asked Jul 15 '11 14:07

Dave


People also ask

What does regex test return?

JavaScript RegExp test() The test() method tests for a match in a string. If it finds a match, it returns true, otherwise it returns false.

What is test() in JavaScript?

test() The test() method executes a search for a match between a regular expression and a specified string. Returns true or false .

What is test() in jquery?

Definition and Usage. The test() method tests for a match in a string. This method returns true if it finds a match, otherwise it returns false.

How to check pattern match in JavaScript?

match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array. Parameters: Here the parameter is “regExp” (i.e. regular expression) which will compare with the given string.


1 Answers

Your syntax is wrong.

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

Unlike PHP, Javascript supports regex literals the syntax /.../ creates a RegExp object.

The RegExp constructor takes a regex as a string, without separators.
Therefore, you could also write new RegExp('^[0-9a-z_]+$', 'i')

like image 187
SLaks Avatar answered Oct 14 '22 04:10

SLaks