asp.net的Regex生日日期

本文关键字:生日 日期 Regex net asp | 更新日期: 2023-09-27 18:21:40

我希望在其中具有日期的字段的regexValidator的regex格式是什么:

dd/MM/yyyy
dd - 01 - 31
MM - 01 - 12
yyyy - 1900 - 2012

非常感谢您的帮助

asp.net的Regex生日日期

您的条件不一定满足合法日期。考虑日期2012年2月30日。正则表达式可以让它通过验证,但没有这样的日期。我建议您改用DateTime.TryParse

MSDN 上的DateTime.TryParse

编辑:我现在意识到,事实上,日期和出生日期之间是有区别的,因为出生日期不可能在未来。

要在验证中强制执行此操作,还应使用CompareTo.DateTime.Now < 0确保日期在过去。

您也可以在客户端进行工作,并使用Date的setFullYear函数来检查日期是否有效。。我为您写了这篇文章,您也可以在运行脚本之前使用提供的regex来测试字段。

<script type="text/javascript">
function checkDate() {
    var content = document.regexForm.input.value;
    var splitResult = content.split("/");
    if(splitResult.length ==3){
        var day = splitResult[0];
        var mon = splitResult[1] - 1; //month is from 0-11 (0:jan,11:dec)
        var yr = splitResult[2];
        //create a new date object set full year with the params
        var myDate = new Date();
        myDate.setFullYear( yr, mon, day);   
        //the function takes in the strings and creates a valid date.. 
        //so if you pass in january 40, the new date is Feb 9th and the month is 02 not 01
        if(myDate.getMonth() != mon){
            alert("not valid");
        }
        else{
            alert("is valid");
        }
    }
    else{
        alert("not valid");
    }
}
</script>
<body>
<form name="regexForm">
dd/mm/yyyy <BR>
<input type="text" name="input">
<input type=button value="run test regex" onClick="checkDate();return true;">
</form>