How can we specify rules for jquery validation plugin by class?

前端 未结 9 1413
一生所求
一生所求 2020-11-27 11:19

The jQuery Validation plugin works great and is very easy to use:

$(\".selector\").validate({
})

Just by setting css classes like \"require

9条回答
  •  一整个雨季
    2020-11-27 12:12

    I've built upon Starx's answer to create a repeatable easy to use function that uses the default methods and creates new error messages for specific classes. considering the fact that your specific class will only be used to override the message once you shouldn't have any conflicts reusing this for many different class names using any existing methods.

    var CreateValidation = function(className, customMessage, validationMethod){
      var objectString = '{"'+ className +'": true}',
      validator = $.validator;
    
      validator.addMethod(
        className,
        validator.methods[validationMethod],
        customMessage
      );
      validator.addClassRules(
        className,
        JSON.parse(objectString)
      );
    };
    

    Usage Example with validation class being "validation-class-firstname":

    CreateValidation('validation-class-firstname', 'Please enter first name', 'required');
    

提交回复
热议问题