Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery unobtrusive validation on composite html control

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.

like image 988
vtortola Avatar asked Jul 22 '11 16:07

vtortola


1 Answers

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>
like image 130
Luca Filosofi Avatar answered Nov 14 '22 01:11

Luca Filosofi