DataAnnotations动态附加属性

mar*_*are 31 asp.net-mvc data-annotations

显然,可以在运行时动态地将DataAnnotation属性附加到对象属性,从而实现动态验证.

有人可以提供代码示例吗?

Joh*_*ell 42

MVC有一个钩子来提供你自己的ModelValidatorProvider.默认情况下,MVC 2使用名为DataAnnotationsModelValidatorProvider的ModelValidatorProvider的子类,该子类能够使用System.DataAnnotations.ComponentModel.ValidationAttribute属性进行验证.

DataAnnotationsModelValidatorProvider使用反射来查找所有ValidationAttributes,并简单地遍历集合以验证模型.您需要做的就是覆盖一个名为GetValidators的方法,并从您选择的任何来源注入您自己的属性.我使用此技术进行常规验证,具有DataType.Email属性的属性始终通过正则表达式传递,并使用此技术从数据库中提取信息以对"非幂"用户应用更严格的验证.

以下示例简单地说"始终要求任何FirstName属性":

 public class CustomMetadataValidationProvider : DataAnnotationsModelValidatorProvider
 {
    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
    {
        //go to db if you want
        //var repository = ((MyBaseController) context.Controller).RepositorySomething;

        //find user if you need it
        var user = context.HttpContext.User;

        if (!string.IsNullOrWhiteSpace(metadata.PropertyName) && metadata.PropertyName == "FirstName")
            attributes = new List<Attribute>() {new RequiredAttribute()};

        return base.GetValidators(metadata, context, attributes);
    }
}
Run Code Online (Sandbox Code Playgroud)

您所要做的就是在Global.asax.cs文件中注册提供程序:

    protected void Application_Start()
    {
        ModelValidatorProviders.Providers.Add(new CustomMetadataValidationProvider());

        AreaRegistration.RegisterAllAreas();

        RegisterRoutes(RouteTable.Routes);
    }
Run Code Online (Sandbox Code Playgroud)

最终结果:

最终结果

使用这个型号:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Birthday { get; set; }
}
Run Code Online (Sandbox Code Playgroud)


Fra*_*ans 8

在global.asax中,您必须先清除ModelValidatorProviders,然后再添加新的.否则它将添加两次每个注释,这将为您提供"不显眼的客户端验证规则中的验证类型名称必须是唯一的." - 错误.

protected void Application_Start()
{
    ModelValidatorProviders.Providers.Clear();
    ModelValidatorProviders.Providers.Add(new CustomMetadataValidationProvider());

    AreaRegistration.RegisterAllAreas();

    RegisterRoutes(RouteTable.Routes);
}
Run Code Online (Sandbox Code Playgroud)