2

I created a custom rule

$(document).ready(function(){
    $("#test-form").validate({
            rules: { 
                test1:{
                    required: true,
                    minlength: 2
                } 
            },
            messages:  {
                test1:{
                    required: "required",
                minlength: "min 2"                      
                }
            }
        });
    // don't really process form
    $("#test-form").submit(function() { return false; });

and I have this HTML code

<input type="text" class="test1"/>

however it doesn't work

if I change to predefined rule , it works

<input type="text" class="number"/>
1
  • Validate() uses the name= attribute from your input, but you don't have one. Add a name="test1" attribute. Commented Oct 31, 2012 at 15:00

2 Answers 2

1

The keys in rules should match the name parameter of the field. Try this:

<input type="text" name="test1" />

Also, you can use debug: true in the options of validate to prevent the form submission while you're testing, instead of returning false from the form submit.

Sign up to request clarification or add additional context in comments.

Comments

1

Rory is right, the rules and messages key should match the 'name' attribute however it looks although you're attempting to create a custom rule which can be added declaratively via a class name?

I think you're therefore looking for the .addMethod() function which can be used like this:

jQuery.validator.addMethod("alphanumeric", function(value, element) {
    return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, and underscores only please");

Which will automatically get picked up via a class name like this:

<input type="text" class="alphanumeric" />

Comments

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.