I have the following control that represents Time:
<div id="xxx">
<input type="text" name="xxx.hour"/>
<input type="text" name="xxx.minute"/>
</div>
Because I want to add validation, I added:
<div id="xxx" data-val="true" data-val-time="Time no valid">
<input type="text" name="xxx.hour"/>
<input type="text" name="xxx.minute"/>
</div>
And I added the adapter and method:
$.validator.addMethod("time_method", function (val, el, params) {
var elementId = $(el).attr('id');
alert('id ' + elementId);
var hour= $(el).children('input[name$=.hour]').val();
var minute= $(el).children('input[name$=.minute]').val();
return hour>= 0 && hour<24 && minute>=0 && minute<23;
});
$.validator.unobtrusive.adapters.add("time", {},
function (options) {
options.rules["time_method"] = true;
options.messages["time_method"] = options.message;
});
But the method "time_method" is never executed, I guess because jquery.validate only applies on input tags, am I right?
What would be the best way to do it?
UPDATE: I know it could be done in several ways, I'm just interested in the possibility of do it this way. I have simplify the problem to show a very small and silly example of what I'm trying to achieve.
demo: https://so.lucafilosofi.com/jquery-unobstrusive-validation-on-composite-html-control
your code should look something like this:
$(function() {
$.validator.addMethod('time_method',function(val, el) {
var re,max;
if (el.id == 'xxx_hour') {
re = /^\d{1,2}$/;
max = 24;
}
if (el.id == 'xxx_minute') {
re = /^\d{2}$/;
max = 59;
}
return re.test(val) && val >= 0 && val <= max;
},
'Time no valid');
$("#xxx").validate({
rules: {
xxx_hour: 'time_method',
xxx_minute: 'time_method',
}
});
});
your html something like:
<form id="xxx">
<input type="text" name="xxx_hour" id="xxx_hour" maxlength="2"/>
<input type="text" name="xxx_minute" id="xxx_minute" maxlength="2"/>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With