最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Validation date input - min and max value - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Nov 4, 2013 at 17:51 witek1902witek1902 2651 gold badge4 silver badges13 bronze badges 2
  • check this: the-art-of-web./html/html5-form-validation – Vitor Venturin Commented Nov 4, 2013 at 17:55
  • input type="text" pattern="\d{1,2}/\d{1,2}/\d{4}" – Vitor Venturin Commented Nov 4, 2013 at 17:56
Add a ment  | 

1 Answer 1

Reset to default 4

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/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/a5Mvt/2/

发布评论

评论列表(0)

  1. 暂无评论