I have two custom validation that perform the validation of a model. The first is a control that I make to see if there are characters in the string "<" and ">", the second is to see if two dates are consecutive.
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;
}
}
Date Validator
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;
}
}
model:
[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; }
}
performing the test known that the first validator, that of angle brackets is displayed, while the second, that of dates, is displayed. But if I post a fair value within queues, passing the validation of angle brackets, the date validator viewing does the error message. Some ideas to make it work properly?
CustomDateCompareValidatorto the class. You apply it to a property in the model - sayDtEndand you provide the other property (DtStart) to it to compare. Suggest you use a foolproof[GreaterThan]or similar validation attribute which will also give you client side validation.