Validation attributes are used to enforce various validation rules in a declarative fashion on classes or class members. All validation attributes derive from the ValidationAttribute base class.
When validated through the ValidationAttribute.Validate
method, this attribute will return an error if the Name
property is null or contains only whitespace.
public class ContactModel
{
[Required(ErrorMessage = "Please provide a name.")]
public string Name { get; set; }
}
The StringLengthAttribute
validates if a string is less than the maximum length of a string. It can optionally specify a minimum length. Both values are inclusive.
public class ContactModel
{
[StringLength(20, MinimumLength = 5, ErrorMessage = "A name must be between five and twenty characters.")]
public string Name { get; set; }
}
The RangeAttribute
gives the maximum and minimum value for a numeric field.
public class Model
{
[Range(0.01, 100.00,ErrorMessage = "Price must be between 0.01 and 100.00")]
public decimal Price { get; set; }
}
The CustomValidationAttribute
class allows a custom static
method to be invoked for validation. The custom method must be static ValidationResult [MethodName] (object input)
.
public class Model
{
[CustomValidation(typeof(MyCustomValidation), "IsNotAnApple")]
public string FavoriteFruit { get; set; }
}
Method declaration:
public static class MyCustomValidation
{
public static ValidationResult IsNotAnApple(object input)
{
var result = ValidationResult.Success;
if (input?.ToString()?.ToUpperInvariant() == "APPLE")
{
result = new ValidationResult("Apples are not allowed.");
}
return result;
}
}