Reputation: 79
I am having difficulties getting this to work. I want to allow a user to choose start date
and end date
, if the start date
is greater than the end date
I want an error message to display. I am using MVC
. This is the code I have on my model.
public class ModelClass : IValidatableObject
{
[Required(ErrorMessage = "ID Number is required")]
[Display(Name = "ID Number:")]
[RegularExpression(@"^(\d{13})$", ErrorMessage = "Enter a 13 digit ID number")]
public Int64 ID_Number { get; set; }
[Required(ErrorMessage = "The start date is required")]
[Display(Name = "Start Date:")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
public DateTime Start_Date { get; set; }
[Required(ErrorMessage = "The end date is required")]
[Display(Name = "End Date:")]
[GreaterThan("Start_Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
public DateTime End_Date { get; set; }
IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
if (End_Date < Start_Date)
{
yield return new ValidationResult("EndDate must be greater than StartDate");
}
}
}
Upvotes: 0
Views: 9301
Reputation: 3491
This is how your model should look like:
public class ModelClass : IValidatableObject
{
[Required(ErrorMessage = "ID Number is required")]
[Display(Name = "ID Number:")]
[RegularExpression(@"^(\d{13})$", ErrorMessage = "Enter a 13 digit ID number")]
public Int64 ID_Number { get; set; }
[Required(ErrorMessage = "The start date is required")]
[Display(Name = "Start Date:")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
public DateTime Start_Date { get; set; }
[Required(ErrorMessage = "The end date is required")]
[Display(Name = "End Date:")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
public DateTime End_Date { get; set; }
IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
if (End_Date < Start_Date)
{
yield return new ValidationResult("EndDate must be greater than StartDate");
}
}
}
After the user pressed on the submit button we need to check that the model is valid.
ModelState.IsValid
will go to you model and will validate the model, If the post model is valid(keeping the rules you decided in your model) then it's valid.
And this is how your action should look like:
[HttpPost]
public ActionResult Create(ModelClass modelClass)
{
if (ModelState.IsValid)
{
db.modelClass.Add(modelClass);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(modelClass);
}
Upvotes: 8