validation - Using jQuery validate rule twice for a field -
i'm trying validate input field holds user's date of birth, , need two checks - 1. make sure user 18 years old , 2. make sure his/her age isn't on 100.
my custom validate method -
$.validator.addmethod( "datediff", function(value, element, diff_years) { var curr_date = new date().getfullyear(); var element_date = date.parse($(element).val()).getfullyear(); return element_date >= curr_date - diff_years; } );
and here's how add rule.
var validator = $('form').validate({ rules: { 'dob': {datediff: 18} }, messages: { dob: {datediff: 'you have 18 or more!'} } });
how reuse datediff
rule twice, can both checks? tried appending datediff
rule, didn't work.
edit: need show 2 distinct messages - example - 1. "you have 18 or more" first condition, , "you cannot more 100" second.
if need 2 unique messages, you'll need 2 unique rules/methods. can put common code single function , call within custom method.
something this...
function datediff(value, diff_years) { var curr_date = new date().getfullyear(); var element_date = date.parse(value.getfullyear(); return element_date >= curr_date - diff_years; } $.validator.addmethod( "over18", function(value, element) { // custom function below // var result = datediff(value, 18); // return true if age greater 18 // return false , error message display }, "you must on 18"); $.validator.addmethod( "under100", function(value, element) { // custom function below // var result = datediff(value, 100); // return true if age less 100 // return false , error message display }, "you must under 100"); $('form').validate({ rules: { dob: { over18: true, under100: true } } });
Comments
Post a Comment