Dave
Dave

Reputation: 1086

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.

Upvotes: 7

Views: 14233

Answers (4)

Vivek kushwaha
Vivek kushwaha

Reputation: 881

use 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);

Upvotes: 0

Mrchief
Mrchief

Reputation: 76258

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

Upvotes: 2

SLaks
SLaks

Reputation: 888223

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')

Upvotes: 13

Igor Dymov
Igor Dymov

Reputation: 16470

Remove quotes from your RegExp:

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

Upvotes: 10

Related Questions