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 data annotations used for validation are given below

Validation

  1. Required: Specify a property as required.
    [Required(ErrorMessage = "CustomerName is mandatory")]
    
  2. RegularExpression: Specifies the regular expression to validate the value of the property.
    [RegularExpression("[a-z]", ErrorMessage = "Invalid character")]
    
  3. Range: Specifies the Range of values between which the property values are checked.
    [Range(1000, 10000, ErrorMessage = "Range should be between 1k & 10k")]
    
  4. StringLength: Specifies the Min & Max length for a string property.
    [StringLength(50, MinimumLength = 5, ErrorMessage = "Minimum char is 5 and maximum char is 10")]
    
  5. MaxLength: Specifies the Max length for the property value.
    [MaxLength(10, ErrorMessage = "Customer Code is exceeding")]
    
  6. MinLength: It is used to check for minimum length.
    [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.

 Validator Attribute

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 a 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.
    [CheckforCaps]
    public string CustomerName { get; set; }
    
    That's it; your Custom Validator is ready for validation. See the following code snippet.
    [CheckforCaps]
    public string CustomerName { get; set; }
    
    public class CheckforCaps : ValidationAttribute
    {
        public CheckforCaps()
            : base("{0} contains invalid character.")
        {
    
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                byte[] ASCIIValues = Encoding.ASCII.GetBytes(value.ToString());
                foreach (byte b in ASCIIValues)
                {
                    if (b <= 65 || b >= 90)
                    {
                        var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                        return new ValidationResult(errorMessage);
    
                    }
                }
            }
            return ValidationResult.Success;
        }
    }
    

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