4

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!

MeltingDog
  • 14,310
  • 43
  • 165
  • 295
  • try this http://stackoverflow.com/questions/4439119/to-check-string-in-jquery-validate – Sibu Jan 08 '13 at 06:29

2 Answers2

11

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}'"
    }
});
Sandeep
  • 2,041
  • 21
  • 34
  • Thanks - I think that is what I need. Dont suppose you know a way to modify it to say equals: "foo" or "bar" or "blah" (ie have multiple correct inputs) – MeltingDog Jan 08 '13 at 06:52
  • You mean u want multiple string validations done?? like the input can be equal to either "foo" or "bar" or "blah"... – Sandeep Jan 08 '13 at 06:55
1

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 */" })
Community
  • 1
  • 1
Cris
  • 12,799
  • 5
  • 35
  • 50
  • Thanks, -but I am not sure how to set this up along side my current script. Would it be something like this http://jsfiddle.net/MeltingDog/CVHKj/ – MeltingDog Jan 08 '13 at 06:32
  • more easier, $.validator.addMethod('Foo', function (value) { return /^Regex/.test(value); }, 'Not valid Foo'); then add this Foo class to your text box – Cris Jan 08 '13 at 06:35