简体   繁体   中英

Reusing Validation Attributes in MVC5

I have been doing a lot of research on validation and how it works. I understand that we can use attributes or even make custom attributes which we can throw over our ViewModels to validate that data. While this is all working fine, I am finding myself to be reusing same combination of attributes on multiple ViewModels.

For example, lets take a "Name", in project X a name, whether it is a Movie Name, Book Name, Person First Name, Last Name, etc... it is a name after all and as such I tend to apply 90% of the validation attributes the same. Required, Minimum length 3, Maximum length 50, only letters, spaces, etc... you get the picture.

Now I end up with a variable that has 5+ attributes stacked on it. These are pre-built attributes that I would prefer not to code again as they are already coded for me. So my question is this:

How can I create a CustomValidateName attribute, which will validate for all of those things, provide different error messages based on what is wrong and at the same time, reuse some of the built in attributes in .NET framework so that I am not re-inventing the wheel. The bottom line here is that whenever I have a Name variable, I can now just put this one attribute instead of the normal 5+.

Use Can create custom Validation for your all validation

For Example :

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.ComponentModel.DataAnnotations;  
using System.Text.RegularExpressions;  

namespace Custom_DataAnnotation_Attribute.Models  
{  
    public class CustomEmailValidator : ValidationAttribute  
    {  
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)  
        {  
            if (value != null)  
            {  
                string email = value.ToString();  

                if (Regex.IsMatch(email, @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", RegexOptions.IgnoreCase))  
                {  
                    return ValidationResult.Success;  
                }  
                else  
                {  
                    return new ValidationResult("Please Enter a Valid Email.");  
                }  
            }  
            else  
            {  
                return new ValidationResult("" + validationContext.DisplayName + " is required");  
            }  
        }  

Above method generate validation for both required nd Email type

You can Add More validation In this method Using If Else or Switch and revert the custome message

At Model:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.ComponentModel.DataAnnotations;  

namespace Custom_DataAnnotation_Attribute.Models  
{  
    public class EmployeeModel  
    {  
        public string Name { get; set; }  

        [CustomEmailValidator]  
        public string Email { get; set; }  
        public string Password { get; set; }  
        public string Mobile { get; set; }          
    }  
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM