aspnet-mvc
  1. aspnet-mvc-custom-validation-attributes

Custom Validation Attributes - (ASP.NET MVC Validation)

ASP.NET MVC provides built-in validation attributes for common scenarios like required fields, string length, data type, and more. Sometimes, however, you may need to define your own custom validation attributes to validate data based on your application's specific requirements. In this tutorial, we'll discuss how to create and use custom validation attributes in ASP.NET MVC.

Syntax

Creating a custom validation attribute in ASP.NET MVC involves creating a new class that inherits from the ValidationAttribute class. The syntax for defining a custom validation attribute is as follows:

public class CustomValidationAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // Add validation logic here
    }
}

Example

Let's create an example custom validation attribute that checks if a string contains a specific substring. Suppose we want to validate that a user's email address contains the domain example.com. We can create a custom validation attribute like this:

public class EmailDomainAttribute : ValidationAttribute
{
    private readonly string _domain;

    public EmailDomainAttribute(string domain)
    {
        _domain = domain;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            var email = value.ToString();
            if (email.EndsWith($"@{_domain}"))
            {
                return ValidationResult.Success;
            }
        }

        return new ValidationResult($"Email must end with '@{_domain}'");
    }
}

This custom validation attribute checks if the string value ends with a specified domain and returns a validation result based on the outcome.

Now, we can apply this validation attribute to a model property like this:

public class User
{
    [EmailDomain("example.com")]
    public string Email { get; set; }
}

This attribute will validate that the email address provided ends with the domain example.com.

Explanation

Custom validation attributes in ASP.NET MVC allow you to define your own validation rules and apply them to model properties. By creating a new class that inherits from the ValidationAttribute class, you can add your own validation logic to the IsValid method.

Use

Custom validation attributes are useful when you need to validate data based on specific business rules or requirements that are not covered by the built-in validation attributes in ASP.NET MVC. By creating your own custom validation attributes, you can keep your validation code organized and reusable.

Important Points

Here are some important points to keep in mind when using custom validation attributes in ASP.NET MVC:

  • Custom validation attributes should inherit from the ValidationAttribute class and override the IsValid method.
  • Custom validation attributes can take arguments in the constructor to configure their behavior.
  • Custom validation attributes can be applied to model properties using the [CustomValidation] attribute.

Summary

In this tutorial, we discussed how to create and use custom validation attributes in ASP.NET MVC. We covered the syntax, example, explanation, use, and important points of using custom validation attributes. With this knowledge, you can create your own custom validation attributes to validate data based on your specific requirements, keeping your validation code organized and reusable.

Published on: