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!

1

2 Answers 2

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}'"
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

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)
You mean u want multiple string validations done?? like the input can be equal to either "foo" or "bar" or "blah"...
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 */" })

2 Comments

Thanks, -but I am not sure how to set this up along side my current script. Would it be something like this jsfiddle.net/MeltingDog/CVHKj
more easier, $.validator.addMethod('Foo', function (value) { return /^Regex/.test(value); }, 'Not valid Foo'); then add this Foo class to your text box

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.