使用自定义验证器防止将来日期和今天日期

Prevent future date and today date using custom validator

本文关键字:日期 将来 今天 自定义 验证      更新时间:2023-09-26

我正在开发一个项目使用实体框架.NET 4。有一个页面注册,其中有一个字段的出生日期。我想验证它,这样出生日期就不会是将来或今天。此外,与今天相比,如果可以回到5年前。

这是我的代码。

Date of Birth:
<asp:RequiredFieldValidator ID="rfv_txtbx_DOB" runat="server" ControlToValidate="txtbx_DOB" CssClass="validator" Display="Dynamic" ErrorMessage="Date of Birth Required" SetFocusOnError="True" Text="*" ValidationGroup="vg" />
<asp:CustomValidator ID="cv_txtbx_DOB" runat="server"  ControlToValidate="txtbx_DOB" CssClass="validator" Display="Dynamic" 
    ErrorMessage="Date of Birth cannot be today or in future" SetFocusOnError="True" Text="*" ValidationGroup="vg" ClientValidationFunction="validateDate"/>
<asp:TextBox ID="txtbx_DOB" runat="server" CssClass="txtbx" Width="200px" />
<ajaxToolkit:CalendarExtender ID="txtbx_DOB_CalendarExtender" runat="server" Enabled="True" Format="dd-MM-yyyy" TargetControlID="txtbx_DOB" />
<script language="javascript" type="text/javascript">
    function Validate(sender, args) {
        var currentDate = new Date().getDate();
            if (args.Value < currentDate)
                args.IsValid = true;
            else
                args.IsValid = false;
        }
</script>
function check_date()
{
var chkdate = document.getElementById("ID OF YOUR TEXT FIELD HERE").value;
var edate = chkdate.split("/");
var spdate = new Date();
var sdd = spdate.getDate();
var smm = spdate.getMonth();
var syyyy = spdate.getFullYear();
var today = new Date(syyyy,smm,sdd).getTime();
var e_date = new Date(edate[2],edate[1]-1,edate[0]).getTime();
if(e_date > today)
 {
    alert("Date is not valid");
    return false;
 }
}

页面加载

protected void Page_Load(object sender, EventArgs e)
{
     Calendar1.EndDate = DateTime.Now;   //to dissable future  Date
}

日历扩展器

中的所有限制http://www.karpach.com/ajaxtoolkit-calendar-extender-tweaks.htm

或者使用下面的java脚本函数

function checkDate(sender, args) {
     if (sender._selectedDate > new Date()) {
          alert("You can select a day earlier than today!");
            sender._selectedDate = new Date();
            // set the date back to the current date
            sender._textbox.set_Value(sender._selectedDate.format(sender._format))
  }