Validation date input - min and max value

2019-06-09 02:23发布

I have one little problem with HTML5.

<input type="date" id="birthday" />

I want check this field in JavaScript.

Min. value - 01-01-1990.

I have no idea how to parse the date object and check that is correct.

Attribute min and max in HTML5 is not working. I must write validation in JavaScript.

1条回答
冷血范
2楼-- · 2019-06-09 02:39

You can use a JavaScript validation library, which uses the HTML5 input attributes like min and max: for example jQuery Validation:

<input id="mydate" name="mydate" type="date" min="2000-01-01" max="2010-31-12" required />

<script>
    $("#mydate").validate();
</script>

Have a look as this fiddle for a working example: http://jsfiddle.net/a5Mvt/1/

In addition you might want to use a library like Modernizr to check for browser support of input[type="date"] and use a datepicker control from jQuery UI or something similar, if it is not supported.


Update: Here's a version, that doesn't use jQuery or any other additional library:

<input id="mydate" name="mydate" type="date" min="2000-01-01" max="2010-31-12" required />
<span id="mydate_error" style="display:none;"></span>

<script>
    var mydate = document.getElementById('mydate'),
        mydateError = document.getElementById('mydate_error');

    mydate.addEventListener('input', function() {
        if (!mydate.value.match(/\d{4}-\d{1,2}-\d{1,2}/)) {
            mydateError.innerHTML = 'Please specify a valid date in the form 1990-02-22';
            mydateError.style.display = 'inherit';
        } else {
            var value = new Date(mydate.value),
                min = new Date(mydate.min),
                max = new Date(mydate.max);
            if (value < min || value > max) {
                mydateError.innerHTML = 'Date has to be between ' + min.toDateString() + ' and ' + max.toDateString();
                mydateError.style.display = 'inherit';
            } else {
                mydateError.style.display = 'none';
            }
        }
    });
</script>

Updated fiddle: http://jsfiddle.net/a5Mvt/2/

查看更多
登录 后发表回答