我试图了解如何将数据传递给我创建的自定义验证。
我有这个模特。
public class MyModel
{
[Required(ErrorMessage="Please enter a Start Date")]
public DateTime StartDate { get; set; }
[Required(ErrorMessage="Please enter an End Date")]
[CustomValidation(typeof(DateCompareValidation), "ValidateDates")]
public DateTime EndDate { get; set; }
}
这是我的验证器。
public class DateCompareValidation
{
public static ValidationResult ValidateDates(object value, ValidationContext context)
{
return new ValidationResult("You are wrong");
}
}
我第一次有公共静态ValidationResult ValidateDates()时,它错误地提示了
"..must match the expected signature: public static ValidationResult ValidateDates(object value, ValidationContext context)."
所以我添加了必要的参数
现在调试类,我看到变量“值”具有结束日期。
我不太了解它如何知道需要什么参数。
另外,我想知道如何传递开始日期或MyModel类,以便可以处理验证逻辑?
仅将逻辑添加到类并实现IValidateObject怎么样?
public class MyClass : IValidatableObject
{
[Required(ErrorMessage="Please enter a Start Date")]
public DateTime? StartDate { get; set; }
[Required(ErrorMessage="Please enter an End Date")]
public DateTime? EndDate { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
if (EndDate < StartDate)
{
yield return new ValidationResult("Invalid date range: End date must be greater then the Start Date");
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句