Created
November 20, 2012 17:20
-
-
Save mkoryak/4119372 to your computer and use it in GitHub Desktop.
add custom error messages to jquery.validate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* you can use the message attribute to provide custom verbose error messages. The error message contains a token {} which will be replaced by the input label. | |
* | |
* Ex: | |
* <label for='firstName'>First Name</label><input id='firstName' name='first_name' class='verbose-error' message='Please enter your {}'/> | |
* the error message will be: Please enter your First Name | |
*/ | |
jQuery.validator.addMethod("verbose-error", function(value, element, param) { | |
var $elem = $(element); | |
if($elem.is('.optional')){ | |
return true; //if this field is marked as optional, do not validate it | |
} | |
var reqd = $.validator.methods.required.call(this, value, element, param); | |
if (!$.validator.messages[element.name] ){ | |
$.validator.messages[element.name] = {}; | |
} | |
var msg = "This field is required."; | |
var label = dogself.getInputLabelText($elem); | |
if(label) { | |
var hasAttr = $elem.filter("*[message]").length; | |
msg = hasAttr ? $elem.attr('message') : "{} is required."; | |
msg = msg.replace(/\{\}/, label); | |
} | |
$.validator.messages['required-msg'] = msg; | |
return reqd; | |
}); | |
jQuery.validator.addClassRules({ | |
'verbose-error': { | |
'verbose-error': true | |
} | |
}); | |
var dogself = { | |
getInputLabelText = function($input){ | |
return $.trim($("label[for='"+$input.attr('id')+"']:not(.error):first").text()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment