user3652383
user3652383

Reputation:

How to check for a certain text value with jQuery.validate()

I'm using jQuery.validate() plugin to validate my website forms. What I am looking to do now is throw up an error when a text field contains a certain string.

For example, say the string to be matched is "penguin". If the user enters "I like penguins" there should be an error, whereas if the user enters anything without the word penguin in it, it should be accepted.

Is there a straightforward way to do this with validate? I just can't figure it out...

Thanks!

Upvotes: 1

Views: 688

Answers (2)

Pratik Joshi
Pratik Joshi

Reputation: 11693

Check FIDDLE

Use Customized method to match text .

jQuery.validator.addMethod("titlePenguin", function(value, element) 
{
    value  = $.trim(value.toLowerCase());
    if(this.optional(element) || /^((?!penguin).)*$/i.test(value))
    {
       return true;
    }
    else
    {
        return false;
    }

},"error ");

Upvotes: 1

Mathieu Labrie Parent
Mathieu Labrie Parent

Reputation: 2606

Before submition of your form, you can perform a custom validation.

if ($("#myinput").val().toLowerCase().indexOf("penguin") >= 0)
{
    return false;
}
//submit the form;

Upvotes: 0

Related Questions