简体   繁体   中英

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!

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}'"
    }
});

referred from Here

$.validator.addMethod(
        "regex",
        function(value, element, regexp) {
            var re = new RegExp(regexp);
            return this.optional(element) || re.test(value);
        },
        "Please check your input."
);

now validate textbox:

$("#Textbox").rules("add", { regex: "/* your regex */" })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM