Validation Attributes
suggest changeValidation 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.
Example: RequiredAttribute
When checked with ValidationAttribute.Validate, this attribute fails if the Name property is null, empty, or contains only whitespace.
public class ContactModel
{
[Required(ErrorMessage = "Please provide a name.")]
public string Name { get; set; }
}
Example: StringLengthAttribute
The StringLengthAttribute validates that a string is at most a given length. 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; }
}
Example: RangeAttribute
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; }
}
Example: CustomValidationAttribute
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;
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents