javascriptvalidationwebshim

Using multiple custom validation constraints on the one element?


<form>
    <input type="date" id="date1" />
    <input type="time" id="time1" />

    <input type="date" id="date2" />
    <input type="time" id="time2" />
</form>

I have two date elements and two time elements on my form. I want to be able to have date1 required if time1 is not empty, and the same for date2 and time2. I also want to have date2 >= date1 if date1 is not empty, and similarly date1 <= date2 if date2 is not empty.

Using the data-dependent-validation jsfiddle sample at http://afarkas.github.io/webshim/demos/demos/forms.html#Custom-validity I can see how to do both of those validation rules, but I can't see how to apply both at the same time. Is this possible?


Solution

  • This currently not possible. But it should be easy to do with DOM scripting conditionally setting required property and changing the min/max properties. In case you need any help let me know. I will create a small fiddle for you.

    For the sake of completeness here is a simple fiddle: http://jsfiddle.net/trixta/sGNwC/

    $('.require-if').each(function () {
        var $date = $('input[type="date"]', this);
        var $time = $('input[type="time"]', this);
        $date
            .on('change.requireif', function () {
                if($date.val()){
                    $time.prop('required', true);
                    if(!$time.prop('value')){
                        $time.prop('value', '00:00');
                    }
                } else {
                    $time.prop('required', false);
                }
            })
            .trigger('change.requireif')
        ;
    });
    

    For the min/max I still used dependent-validation and for the required part I wrote the small script above.