Reputation: 755
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?
Upvotes: 2
Views: 2558
Reputation:
Because property Age
is typeof int
, it is always required (an int
cannot be null
) and if you leave the textbox empty, a null
value is submitted and the Required validation is executed first and that error message is displayed.
Change you property to be nullable
public int? Age { get; set; }
Note that it works for your Name
property because its string
which is nullable by default.
As a side note, you should consider implementing IClientValidatable
so that you can get client side validation as well. Refer The Complete Guide To Validation In ASP.NET MVC 3 - Part 2.
Upvotes: 1