EibergDK
EibergDK

Reputation: 564

jQuery match regexp

Let's say i have the following text input:

<input class="required-field" type="text" name="create-user-username" pattern="/^[0-9]+$/" />

Somewhere in my JS i (would like to) use the follow snippet in my form validation:

$('.required-field').each(function() {
    var inputVal = $(this).val();
    var pattern = $(this).attr('pattern');

    if (pattern !== 'undefined') {
        if (inputVal.match(pattern)) {
            alert('Input is not valid');
        }        
    }

});

However, the match is not working and I have failed in finding a working solution...

The form is completed by the user in steps, and each pages are validated before you can move to next step. That why I'm not using jQuery .validate....

Upvotes: 1

Views: 285

Answers (3)

Mark Pieszak - Trilon.io
Mark Pieszak - Trilon.io

Reputation: 67011

jsFiddle DEMO

You are missing a parenthesis.

if (inputVal.match(pattern)) // <-- this one

And as @Christoph had mentioned you are trying to match against a string, and can either use the .replace() method to remove the outer / /, or change your pattern in the input element itself to be:

input pattern="^[0-9]+$"

And change your pattern variable to:

var pattern = new RegExp($(this).attr('pattern')); // now it'll all work

On a side note, always make sure you check your console log (you would have seen the typical Uncaught SyntaxError: Unexpected token {

Also when checking for undefined, the best way is to do:

typeof(pattern) !== 'undefined'

Upvotes: 3

Muthu Kumaran
Muthu Kumaran

Reputation: 17910

Currently your patterns is string and you need to convert to a real real pattern using new RegExp().

Also remove slashes / from pattern="/^[0-9]+$/" which will not be required because new RegExp() will automatically add the slashes.

See the code,

<input class="required-field" type="text" name="create-user-username" pattern="^[0-9]+$" value=""/>
​ 


$('.required-field').each(function() {
    var inputVal = $(this).val();
    var pattern = $(this).attr('pattern');

    if (pattern != 'undefined') {
        pattern =  new RegExp(pattern)
        if (inputVal.match(pattern)){
            alert('Input is not valid');
        }        
    }

});​

Demo: http://jsfiddle.net/43eLD/1/

Upvotes: 0

Christoph
Christoph

Reputation: 51201

pattern is a string, thus is needs to be:

$(this).attr('pattern').replace(/\//g,"");

if (!inputVal.match(new RegExp(pattern))) { // also you missed a ! for negation

also, use either

if (!pattern) // uses falsyness of "undefined" - also catches the empty string

// or

if ( typeof pattern !== "undefined")

and fix your mismatching parens: if (inputVal.match(pattern) // <- missing )

Upvotes: 2

Related Questions