简体   繁体   English

重用MVC5中的验证属性

[英]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. 我知道我们可以使用属性,甚至可以创建自定义属性,然后可以将其放到ViewModel上以验证该数据。 While this is all working fine, I am finding myself to be reusing same combination of attributes on multiple ViewModels. 尽管一切正常,但我发现自己正在多个ViewModel上重复使用相同的属性组合。

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. 例如,让我们以一个“名称”作为名称,在项目X中使用一个名称,无论它是电影名称,书名,人名,姓氏等等。。。毕竟这是一个名称,因此我倾向于使用90%的验证属性相同。 Required, Minimum length 3, Maximum length 50, only letters, spaces, etc... you get the picture. 图片,必填,最小长度3,最大长度50,仅字母,空格等。

Now I end up with a variable that has 5+ attributes stacked on it. 现在,我得到一个变量,该变量具有5个以上的属性。 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. 我该如何创建CustomValidateName属性,以对所有这些内容进行验证,并根据错误内容提供不同的错误消息,同时又重用.NET框架中的某些内置属性,因此我不会发明轮子。 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+. 最重要的是,只要我有一个Name变量,我现在就可以放一个属性,而不是普通的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 上面的方法为两种必需的nd电子邮件类型生成验证

You can Add More validation In this method Using If Else or Switch and revert the custome message 您可以在此方法中使用If If Else或Switch来添加更多验证,并还原自定义消息

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; }          
    }  
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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