I have a custom validation attribute:
public class RequireIfPropertyIsFalseAttribute : ValidationAttribute
{
private string basisProperty { get; set; }
public RequireIfPropertyIsFalseAttribute(string basisProperty)
{
this.basisProperty = basisProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var basisProp = validationContext.ObjectType.GetProperty(basisProperty);
var isFalse = !(bool)basisProp.GetValue(validationContext.ObjectInstance, null);
if (isFalse)
{
if (value == null || (value.GetType() == typeof(string) && string.IsNullOrEmpty(((string)value).Trim())))
return new ValidationResult(this.ErrorMessage);
}
return ValidationResult.Success;
}
}
I use it for both Model properties:
public bool NoAgeProvided { get; set; }
[RequireIfPropertyIsFalse(nameof(NoAgeProvided), ErrorMessage = "This is required")]
[Display(Name = "Age")]
public int Age { get; set; }
public bool NoNameProvided { get; set; }
[RequireIfPropertyIsFalse(nameof(NoNameProvided), ErrorMessage = "This is required")]
[Display(Name = "Name")]
public string Name { get; set; }
Upon validation, the Name validation message shows "This is required". However, for the Age property, "The Age field is required" is displaying on the validation message. What am I doing wrong? How can I display the set ErrorMessage?