0

I want to create a custom validation rule, which uses some different methods to check the input. One of them, is required rule.

But the code doesn't work. It ignores empty inputs and says they're valid.

The code:

$("#test-form").validate({
    rules: {
        test: {
            required: true
        }
    }
});

Live Example: http://jsfiddle.net/u5now2e5/

What's wrong? Note that, I don't want to use required css class. Because it depends on some other fields.

Sparky
  • 98,165
  • 25
  • 199
  • 285
mrdaliri
  • 7,148
  • 22
  • 73
  • 107
  • 1
    This wont work because test is a classname, but rules are set/ defined via the name of the field. If you want to add a custom class rule use: addClassRules: http://jqueryvalidation.org/jQuery.validator.addClassRules/ – axel.michel Dec 05 '14 at 16:27
  • You can use http://jqueryvalidation.org/jQuery.validator.addClassRules/ – thanh Dec 05 '14 at 16:29
  • Note that `.addClassRules()` is limited to simply creating a "compound" rule composed of standard rules and declaring that "compound" rule to fields using a class name. If you want to create a whole new rule, or a rule you can declare within `.validate()`, you must use `.addMethod()`. – Sparky Dec 05 '14 at 16:35

1 Answers1

0

You must have a unique name attribute on the input; and when you declare rules within .validate() it can only be referenced via that name attribute.

<input type="text" id="input-1" class="test" name="test" />

jQuery:

$("#test-form").validate({
    rules: {
        test: {  // <- NAME of input field
            required: true
        }
    }
});

http://jsfiddle.net/u5now2e5/2/


To create a "custom" rule, you would use the .addMethod() method. But again, every input must still have a unique name attribute, and when you declare the rule within .validate(), it can only be referenced by name.

Sparky
  • 98,165
  • 25
  • 199
  • 285