Custom validation is useful when the inbuilt validation attribute doesn’t solve our validation problem. We have already talked about validation attributes while creating Models in above points. Like Range, StringLength, Required etc.
In this example, we will create a validation attribute that let us define a Date type of field that only accepts a date earlier than today’s date.
To do that, please create a class like following
VALIDATION CLASS CODE
using System.ComponentModel.DataAnnotations; public class DateValidationAttribute : ValidationAttribute { public override bool IsValid(object value) { DateTime todayDate = Convert.ToDateTime(value); return todayDate <= DateTime.Now; } }
Notice that above class name ends with “Attribute” word, its a naming convention we should follow while declaring a class for the attribute. Above class inherits a class named “ValidationAttribute”
that has few virtual method overloads named IsValid (most important, other virtual methods are also there) that we need to override in our validation class.
In the above class we are overriding IsValid
method that accepts the value as object of the property on which this attribute will be applied. In this case, if the field date value is lesser than current date, it returns true otherwise false (ie. the validation failed).
To use this validation attribute, we write as an attribute to the model property as we write other in-built validation attributes
MODEL CLASS CODE
[DateValidation] public DateTime? BirthDate { get; set; } [DateValidation(ErrorMessage = "Sorry, the date can't be later than today's date")] public DateTime? MyBirthDate { get; set; }
In the first case, we have just placed the [DateValidation] attribute on the BirthDate property of the Model. This gives following error when date is passed later than today.
If we want a custom error to be displayed if the validation fails for this field, then we need to pass the “ErrorMessage” value with the attribute and it will works like below.
Other example of custom validaiton
Similarly, we can also overload other IsValid method that accepts ValidationContext as 2nd parameter.
VALIDATION CLASS CODE
public class AdultAgeValidationAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext context) { int givenAge = int.Parse(value.ToString()); if (givenAge < 18) { return new ValidationResult("The age must be greater than 18"); } else { return ValidationResult.Success; } } }
Here, the error message is being sent from this validation class itself.
MODEL CLASS CODE
[AdultAgeValidation] public int Age { get; set; }
Above Age property only accepts age that is greater than 18 otherwise it throws error "The age must be greater than 18".
Views: 21152 | Post Order: 87