开发者

jQuery.validate with custom errors per control

开发者 https://www.devze.com 2023-01-23 19:16 出处:网络
I\'m currently using jQuery.validate as a plugin for validation... my problem comes into play where I want to use custom error messages based on the validation type per control.

I'm currently using jQuery.validate as a plugin for validation... my problem comes into play where I want to use custom error messages based on the validation type per control.

I'm using the metadata extension for this, and I've thought about just having a generic formatter that gets passed in.. so the error message is literally "{0}" and when I specify my validators, I can do so inline...

<input ... data-meta='{
    validate: {
       date: [ "real error message here" ]
    }
}' />

With myDate defined as...

// override default date...
$.validator.addMethod("date", function(value, element) { 
    //use Date.js's parse instead of default's new Date(开发者_如何学运维) matching.
    return this.optional(element) || !!Date.parse(value);
}, "{0}");

I can't help but to feel a little "dirty" doing this though... does anyone have a better solution?


The metadata version for validation already has built-in support for messages, for example:

<input ... 
 data-meta='{validate:{date:true,messages:{date:"real error message here"}}}' />

You can see it in action in the jQuery validation metadata demo here.

0

精彩评论

暂无评论...
验证码 换一张
取 消