Adding Custom Validation in MVC

DataAnnotation plays a vital role in added validation to properties while designing the model itself. This validation can be added for both the client side and the server side.

You understand that decorating the properties in a model with an Attribute can make that property eligible for Validation.

Some of the DataAnnotation used for validation are given below

validation

  1. Required

    Specify a property as required.
    1. [Required(ErrorMessage="CustomerName is mandatory")] 
  2. RegularExpression

    Specifies the regular expression to validate the value of the property.
    1. [RegularExpression("[a-z]", ErrorMessage = "Invalid character")] 
  3. Range

    Specifies the Range of values between which the property values are checked.
    1. [Range(1000,10000,ErrorMessage="Range should be between 1k & 10k")] 
  4. StringLength

    Specifies the Min & Max length for a string property.
    1. [StringLength(50, MinimumLength = 5, ErrorMessage = "Minimum char is 5 and maximum char is 10")] 
  5. MaxLength

    Specifies the Max length for the property value.
    1. [MaxLength(10,ErrorMessage="Customer Code is exceeding")] 
  6. MinLength

    It is used to check for minimum length.
    1. [MinLength(5, ErrorMessage = "Customer Code is too small")] 

This article explains how to create our own Custom Validator Attribute and attach it to the properties.

Custom validator

I am creating a Custom Validator that will validate the Customer Name property, whether all characters in the name are in upper case. The following is the procedure to create Custom Validator.
  1. Create a class that will extend ValidationAttribute
  2. Override the IsValid method. Write logic to check for upper case letters and return an error if a letter is not upper case else return ValidationResult as Success.
  3. Decorate the model property with the Custom Validator class name as in the following:
    1. [CheckforCaps]  
    2. public string CustomerName { getset; } 
    That's it; your Custom Validator is ready for validation. See the following code snippet.
    1. public class CheckforCaps : ValidationAttribute  
    2. {  
    3.     public CheckforCaps()  
    4.         : base("{0} contains invalid character.")  
    5.     {  
    6.   
    7.     }  
    8.   
    9.     protected override ValidationResult IsValid(object value, ValidationContext validationContext)  
    10.     {  
    11.         if (value != null)  
    12.         {  
    13.             byte[] ASCIIValues = Encoding.ASCII.GetBytes(value.ToString());  
    14.             foreach (byte b in ASCIIValues)  
    15.             {  
    16.                  if (b <= 65 || b >= 90)  
    17.                  {  
    18.                     var errorMessage = FormatErrorMessage(validationContext.DisplayName);  
    19.                     return new ValidationResult(errorMessage);  
    20.   
    21.                 }  
    22.             }  
    23.         }  
    24.         return ValidationResult.Success;  
    25.     }  

Conclusion

I hope you liked this article about creating a Custom Validator and attaching it with a Model property. Please share your comments, it is valuable to me and keep sharing no matter what :)


Similar Articles