Custom Validation for Date Field
In this article We learn about how to using Custom Validator for simple date field validation
=======================================================Steps to be fllowed to write a custom Validator:
------------------------------------------------------
Scenario:
Date Of Birth Validation:
//If the user enters date greater than the current
//date of the server then display an error message
1)Create a hidden field control in aspx page in order to have server date rather than client machine date<asp:HiddenField ID="hdnCurrentDate" runat="server" />
2)Convert the date to required format from code behind aspx.cs file
//Setting the current date value to hidden field
//This Current date is sent to a function to check the
//Date Of Birth hdnCurrentDate.Value = DateTime.Now.ToString("dd-MM-yyyy");
3)Add a Custom validator for the required date field<asp:CustomValidator ID="custDateOfBirth" runat="server" ControlToValidate="txtBirthDate" ClientValidationFunction="CheckDate" ErrorMessage="Enter less than the current date" CssClass="ClsRedtext" SetFocusOnError="true"></asp:CustomValidator>
4)Write a javascript function to handle the validation
<script>
function CheckDate(oSrc,args)
{
//The below two ids are view source of the aspx file
//of the respective controls one is Entered date and the other is hidden field date
//('ctl00_ContentPlaceHolder1_txtBirthDate')
//('ctl00_ContentPlaceHolder1_hdnCurrentDate')
var dateOfBirthClientID = document.getElementById('ctl00_ContentPlaceHolder1_txtBirthDate');
var systemDateClientID = document.getElementById('ctl00_ContentPlaceHolder1_hdnCurrentDate');
var dateOfBirth = dateOfBirthClientID.value;
var systemDate = systemDateClientID.value;
var ArrDob = dateOfBirth.split("-");
var DobMonth = ArrDob[0];
var DobDate = ArrDob[1];
var DobYear = ArrDob[2];
var ArrSysDate = systemDate.split("-");
var SysDate = ArrSysDate[0];
var SysMonth = ArrSysDate[1];
var SysYear = ArrSysDate[2];
//alert("DobYear="+DobYear+"SysYear ="+SysYear +"DobMonth="+DobMonth+"SysMonth="+SysMonth+"DobDate="+DobDate+"SysDate="+SysDate);
if(DobYear > SysYear)
{
args.IsValid = false;
return;
}
else if((DobYear == SysYear) && (DobMonth > SysMonth))
{
args.IsValid = false;
return;
}
else if((DobYear == SysYear) && (DobMonth == SysMonth) && (DobDate > SysDate))
{
args.IsValid = false;
return;
}
args.IsValid = true;
}
</script>
=======================================================Its a good example to start with a small custom control for starters
nice stuff and give some more