Monday, January 29, 2007

Date validations

Ok, many other times I come across date validation requirements and typically to validate a date to be either be a future date only (like departure date) or not in future date (like DOB). In these cases one method I use is to have a asp:CustomValidator with OnServerValidate to have the validation code on the server side. For these two scenarios I typically have something like this in my (generic) app helper class:

#region "Date validations"

public void noFutureDate(object source, ServerValidateEventArgs args)

{

DateTime dt;

/*Date validations:

* Must be a valid date

* Must not be a future date*/

if ((DateTime.TryParse(args.Value, out dt) == false) ||

(dt > DateTime.Today))

{

args.IsValid = false;

}

}

public void noPastDate(object source, ServerValidateEventArgs args)

{

DateTime dt;

/*Date validations:

* Must be a valid date

* Must not be a past date*/

if ((DateTime.TryParse(args.Value, out dt) == false) ||

(dt < DateTime.Today))

{

args.IsValid = false;

}

}

#endregion "Date validations"



Love coding!

No comments: