Creating a custom validation attribute

suggest change

Custom validation attributes can be created by deriving from the ValidationAttribute base class, then overriding virtual methods as needed.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class NotABananaAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var inputValue = value as string;
        var isValid = true;

        if (!string.IsNullOrEmpty(inputValue))
        {
            isValid = inputValue.ToUpperInvariant() != "BANANA";
        }

        return isValid;
    }
}

This attribute can then be used like this:

public class Model
{
    [NotABanana(ErrorMessage = "Bananas are not allowed.")]
    public string FavoriteFruit { get; set; }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents