Javascript 验证出生日期大于今天?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42713089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:23:20  来源:igfitidea点击:

Validate date of birth greater than today?

javascriptjqueryhtml

提问by c.grey

How to validate html <input type='date'/>is greater than today?

如何验证 html<input type='date'/>比今天更大?

The following is my code:

以下是我的代码:

<div class="form-group">
<label class="col-sm-2" for='id_dateOfBirth'>Birth Date </label>
<div class="col-sm-10">
    <input class='form-control' name="dateOfBirth" id='id_dateOfBirth' type='date'>
</div>

I want to check whether date is greater than today using JavaScript.

我想使用 JavaScript 检查日期是否大于今天。

回答by Nitesh Goyal

What I understand from your question is - "Before posting the form, you'd like to check if the DOB field has a date that must not be greater than today's date.". If this is correct, then try this, Hope this help -

我从您的问题中了解到 - “在发布表单之前,您想检查 DOB 字段的日期是否不得大于今天的日期。”。如果这是正确的,那么试试这个,希望这有助于 -

<script type="text/javascript">
    function checkDOB() {
        var dateString = document.getElementById('id_dateOfBirth').value;
        var myDate = new Date(dateString);
        var today = new Date();
        if ( myDate > today ) { 
            $('#id_dateOfBirth').after('<p>You cannot enter a date in the future!.</p>');
            return false;
        }
        return true;
    }
</script>

回答by MaoStream

If you can use php do: <input type="date" name="date1" max=<?php echo date('Y-m-d'); >

如果您可以使用 php,请执行以下操作: <input type="date" name="date1" max=<?php echo date('Y-m-d'); >

if only js:

如果只有js:

document.getElementById("id_dateOfBirth").setAttribute("max", today);

where today is eg 2017-03-10 to get this date use eg :

今天是例如 2017-03-10 获得这个日期使用例如:

      new Date().toJSON().split('T')[0]