我有两个自定义验证,用于执行模型验证。第一个是我用来查看字符串“<”中是否有字符的控件和“>”,第二个是查看两个日期是否连续。
Angle Brackets Validator
public class AngleBracketsValidator : ValidationAttribute
{
public override Boolean IsValid(Object value)
{
Boolean isValid = true;
if (value != null && (value.ToString().Contains('<') || value.ToString().Contains('>')))
{
isValid = false;
}
return isValid;
}
}
日期验证器
public class CustomDateCompareValidator : ValidationAttribute
{
public String PropertyDateStartToCompare { get; set; }
public String PropertyDateEndToCompare { get; set; }
public CustomDateCompareValidator(string propertyDateStartToCompare, string propertyDateEndToCompare)
{
PropertyDateStartToCompare = propertyDateStartToCompare;
PropertyDateEndToCompare = propertyDateEndToCompare;
}
public override Boolean IsValid(Object value)
{
Type objectType = value.GetType();
PropertyInfo[] neededProperties =
objectType.GetProperties()
.Where(propertyInfo => propertyInfo.Name == PropertyDateStartToCompare || propertyInfo.Name == PropertyDateEndToCompare)
.ToArray();
if (neededProperties.Count() != 2)
{
throw new ApplicationException("CustomDateCompareValidator error on " + objectType.Name);
}
Boolean isValid = true;
if (Convert.ToDateTime(neededProperties[0].GetValue(value, null)) != Convert.ToDateTime("01/01/0001") && Convert.ToDateTime(neededProperties[1].GetValue(value, null)) != Convert.ToDateTime("01/01/0001"))
{
if (Convert.ToDateTime(neededProperties[0].GetValue(value, null)) > Convert.ToDateTime(neededProperties[1].GetValue(value, null)))
{
isValid = false;
}
}
return isValid;
}
}
模型:
[Serializable]
[CustomDateCompareValidator("DtStart", "DtEnd", ErrorMessage = "the start date is greater than that of the end.")]
public class ProjModel
{
[Display(Name = "Codice:")]
[AllowHtml]
[AngleBracketsValidator(ErrorMessage = "Code can not contain angle bracket.")]
public string Code { get; set; }
[Display(Name = "Date Start:")]
public DateTime? DtStart { get; set; }
[Display(Name = "Date End:")]
public DateTime? DtEnd { get; set; }
}
执行测试,知道显示第一个验证器,尖括号的验证器,而第二个验证器,即日期的验证器,显示。但是,如果我在队列中发布公平值,通过尖括号验证,则查看日期验证程序会执行错误消息。 一些让它运作正常的想法?