Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Form Validation plugin - validate specific string?

I have a form that uses this plugin:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Works great - but I cant figure how to validate by a specific string in-putted into a text field. For example, I want to create a rule that only validates a field if the users input is "foo".

There is documentation here http://docs.jquery.com/Plugins/Validation#API_Documentation

But none of them seem to be the one I want. Does anyone know a way to get round this?

Thanks!

like image 544
MeltingDog Avatar asked Dec 16 '22 15:12

MeltingDog


1 Answers

Simple one...

$.validator.addMethod("equals", function(value, element, string) {
    return value === string;
}, $.validator.format("Please enter '{0}'"));
$("#form").validate({
    rules: {            
        name: {
            required: true,
            equals: "foo"
        }
    }
});

Updated according to your requirement

$.validator.addMethod("equals", function(value, element, string) {
    return $.inArray(value, string) !== -1;
}, $.validator.format("Please enter '{0}'"));
$("#form").validate({
    rules: {            
        name: {
            required: true,
            equals: ["foo", "bar", 'blah"]
        }
    },
    messages: {
        name: "Please enter either '{0}' or '{1}' or '{2}'"
    }
});
like image 95
Sandeep Avatar answered Dec 26 '22 19:12

Sandeep