我有这样定义的模型:
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;
}
我正在验证如下:
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)) });
}
验证会发生什么,它首先只调用&#34;必需&#34;属性 - 例如,如果开始日期晚于结束日期且指令为空,则仅返回指令不能为空的消息。一旦它们不为null,它将返回开始/结束日期错误消息。
有没有办法让它预先进行所有验证而不是两次尝试?
另外,有没有办法将开始/结束验证添加到客户端结果?