I have a model defined this way:
public class AdvisoryViewModel : IValidatableObject
{
[Display(Name = "Start Date")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true, ConvertEmptyStringToNull = true)]
public DateTime? StartDate { get; set; }
[Display(Name = "End Date")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true, ConvertEmptyStringToNull = true)]
public DateTime? EndDate { get; set; }
[Display(Name = "Instructions")]
[Required(ErrorMessage = "Instructions are required")]
[MaxLength(500, ErrorMessage = "Instructions cannot be longer than 500 characters.")]
public string Instruction { get; set; }
IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
List<ValidationResult> results = new List<ValidationResult>();
if (StartDate.HasValue &&
EndDate.HasValue &&
StartDate.Value > EndDate.Value)
{
ValidationResult result = new ValidationResult("Start date must be after end date.");
results.Add(result);
}
return results;
}
And I am validating it as follows:
var validationResults = new List<ValidationResult>();
if (!Validator.TryValidateObject(advisoryViewModel, new ValidationContext(advisoryViewModel), validationResults, true))
{
return Json(new { success = false, message = string.Join("; ", validationResults.Select(r => r.ErrorMessage)) });
}
What happens on validation is it first only calls the "Required" attributes - for example, if the start date is later than end date AND the instructions are null, it returns with only the message that instructions cannot be null. Once they are not null, it returns the start/end date error message.
Is there a way to have it do ALL of the validations up front rather than two attempts?
Also, is there a way the start/end validation can be added to client side results?