JavaScript 日期验证函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13624154/
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-10-26 19:18:55  来源:igfitidea点击:

JavaScript Date Validation Function

javascript

提问by gautam vegeta

Can anyone explain how does the foll JS function validate date which needs to be of the form mm/dd/yyyy.

任何人都可以解释 foll JS 函数如何验证需要采用 mm/dd/yyyy 形式的日期。

<script type="text/javascript">

function checkdate(input){
    var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
    var returnval=false
    if (!validformat.test(input.value))
        alert("Invalid Date Format. Please correct and submit again.")
    else{ //Detailed check for valid date ranges
        var monthfield=input.value.split("/")[0]
        var dayfield=input.value.split("/")[1]
        var yearfield=input.value.split("/")[2]
        var dayobj = new Date(yearfield, monthfield-1, dayfield)
        if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
            alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
        else
            returnval=true
    }
    if (returnval==false) input.select()
        return returnval
}
</script>

回答by techfoobar

The first part uses regex to check if the value is in the required format mm/dd/yyyy. This is ensure that validation fails if it not a /delimited string with 2, 2 and 4 numbers respectively.

第一部分使用正则表达式检查值是否符合要求的格式mm/dd/yyyy。如果它不是/分别具有 2、2 和 4 个数字的分隔字符串,则确保验证失败。

The second part creates a date object using the individual dd, mmand yyyyvalues and checks the properties of the created object with the original values in the input. This is to ensure that the validation fails for values like 02/31/2015

第二部分使用个人和值创建日期对象ddmm并使用yyyy输入中的原始值检查所创建对象的属性。这是为了确保验证对于像这样的值失败02/31/2015

if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))

if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))

The above statement is to ensure that the created object reflects the same values that were used for creating it. Also, note that month index starts at 0, hence the -1during creation and +1during checking.

上面的语句是为了确保创建的对象反映用于创建它的相同值。另请注意,月份索引从 开始0,因此-1在创建+1期间和检查期间。