Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery RegEx Validation

I am wanting to check if an input field has the attribute "pattern" and if so, preform a regex check aganst said pattern.I know this is already done by HTML5, but I am wanting to handle the event myself. I am receiving this error: Uncaught TypeError: Object a-zA-Z has no method 'test'

 ///Check Perform Reg///////////////////////////////////////////////////////
         if ($(this).attr("pattern")) {
             var reg = $(this).attr("pattern");
             var currentValue = $(this).val();


             if (reg.test(currentValue)) {
                 $(this).after($error.clone().text("Invalid Input.Try Again."));
                 $(".error:hidden").fadeIn("slow");
                 hasError = true;
                 return false;
             }

             }
        ///////////////////////////////////////////////////////////////////////////

Still no luck,

also here is my html:

<div>
    <input class="formInput" name="First Name" pattern="^[A-Za-z_-][A-Za-z0-9_-]*$" type="text"  id="frmFirst" min="2" maxlength="30"  required="required"/>
    <span>First Name</span>
</div>
like image 815
user1265533 Avatar asked Apr 06 '12 03:04

user1265533


2 Answers

Normally regular expression with javascript / jquery handle like

var reg = /pattern/;
if (reg.test($(this).val())) {
    // perform some task
}
like image 120
irfanmcsd Avatar answered Oct 04 '22 08:10

irfanmcsd


As already mentioned by others you need to use an object instead of the string returned by the jQuery attr() method. You can see the difference between the two here.

Will return "string":

var reg = $(this).attr("pattern");
console.log(typeof reg)

Will return with "object":

var reg = new RegExp($(this).attr("pattern"));
console.log(typeof reg);

So if you replace:

var reg = $(this).attr("pattern");

With:

var reg = new RegExp($(this).attr("pattern"));

The Uncaught TypeError: Object a-zA-Z has no method 'test' error will disappear

...but your validation still won't work very well. Your conditional logic says if the regex test returns TRUE then handle an error:

if (reg.test(currentValue)) {
    //error handling
}

Instead it should handle an error if the test returns FALSE:

if (!reg.test(currentValue)) {
    //error handling
}

This should work for you.

like image 45
deezy Avatar answered Oct 04 '22 10:10

deezy