How to use HTML5 to validate a date range?

前端 未结 5 1038
清酒与你
清酒与你 2021-01-12 17:15

Alternatively, is it possible to validate against another field\'s value with html5?

A common example would be selecting a date range where \"from\" date sh

5条回答
  •  旧时难觅i
    2021-01-12 17:56

    Here, Web Components are very useful, however they are not full supported in all browsers yet .

    The idea is to create a simple html Element, with two children (from and to) as the following:

    then create a template, which defines how the date picker should look:

    
    

    the select parameter defines, where the value is taken from so the first input field takes the first div from the "#fromToDate".

    Last we have to populate the "shadow root" and define the logic:

    var shadow = document.querySelector('#fromToDate').webkitCreateShadowRoot(),
        template = document.querySelector('#fromToDateTemplate');
    shadow.appendChild(template.content);
    
    
    shadow.querySelector(".fromDate").addEventListener("change", function (e) {
        var to = this.value;
    
        shadow.querySelector(".toDate").setAttribute("min", this.value);
    });
    
    template.remove();
    

    In the end two input fields are renderd and when selecting a date in the first datepicker, the second datepicker can't pick any lower data.

    Fiddler example: http://jsfiddle.net/cMS9A/

    Advantages:

    • Build as widget
    • Easy to reause
    • won't break pages
    • can be styled independently

    Disadvantages:

    • Not supported in all browsers yet

    Future reading:

    • http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/
    • http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-201/
    • https://dvcs.w3.org/hg/webcomponents/raw-file/tip/explainer/index.html

提交回复
热议问题