Has anyone seen an MVC3 data annotation for Date validation that requires a single selected date to be equal to or greater than current date?
If there\'s already a t
Create a custom attribute.
public class CheckDateRangeAttribute: ValidationAttribute {
protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
DateTime dt = (DateTime)value;
if (dt >= DateTime.UtcNow) {
return ValidationResult.Success;
}
return new ValidationResult(ErrorMessage ?? "Make sure your date is >= than today");
}
}
code was written off the cuff so fix any errors :)
Use [Remote]
for special validations, simple and easy:
Your model:
[Remote("ValidateDateEqualOrGreater", HttpMethod="Post",
ErrorMessage = "Date isn't equal or greater than current date.")]
public DateTime Date { get; set; }
//other properties
Your action:
[HttpPost]
public ActionResult ValidateDateEqualOrGreater(DateTime Date)
{
// validate your date here and return True if validated
if(Date >= DateTime.Now)
{
return Json(true);
}
return Json(false);
}
Simple way to accomplish this task is using CompareValidator
.
The code below uses AjaxControlToolKit's CalendarExtender
.
Copy the below code to your HTML directive
<asp:TextBox ID="txtCompletionDate" runat="server" CssClass="txtNormal"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1" TargetControlID="txtCompletionDate"
Format="dd/MM/yyyy" runat="server">
</cc1:CalendarExtender>
<asp:RequiredFieldValidator ID="rfvCompletionDate" runat="server" ControlToValidate="txtCompletionDate"
CssClass="labelError" ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:CompareValidator ID="cvDate" runat="server" ControlToCompare="hiddenbox" ErrorMessage="*"
ControlToValidate="txtCompletionDate" CssClass="labelError" ToolTip="Completion Date should be greater than or equal to Today"
Operator="GreaterThanEqual" Type="Date"></asp:CompareValidator>
<asp:TextBox ID="hiddenbox" runat="server" CssClass="hiddenbox">
</asp:TextBox>
add the below line in the CSS
.hiddenbox {display:none;}