ASP.NET MVC 3 数据注释 : Add validation dynamically

标签 asp.net validation asp.net-mvc-3 dynamic data-annotations

我是数据注释新手。我想知道是否可以(以及如何)动态添加一些验证。解释原因非常广泛,但我有一个在创建时接收和对象的 ViewModel。在该对象中,我必须检查某些属性,并根据其值我应该进行或不进行一些验证。

一个例子:

public class ProfileViewModel
{
    [Required(ErrorMessage = "The field {0} is required")]
    [Display(Name = "Client Code")]
    public int ClientCode { get; set; }

    [Required(ErrorMessage = "The field {0} is required")]
    [StringLength(100, ErrorMessage = "The field {0} must have up to 100 characters.")]
    [Display(Name = "Company")]
    public string Company { get; set; }

    [StringLength(50, ErrorMessage = "The field {0} must have up to 50 characters.")]
    [Display(Name = "Name")]
    public string Name { get; set; }

    [StringLength(50, ErrorMessage = "The field {0} must have up to 50 characters.")]
    [Display(Name = "LastName")]
    public string LastName { get; set; }

    public ProfileViewModel(User usr)
    {
        if (usuario.ClientCode != null)
        {
            ClientCode = Convert.ToInt32(usr.ClientCode);
        }
        else
        {
             //ClientCode and Company are not yet required.
             //Name and LastName are now required.
        }
        Company = usr.Company;
        Name = usr.Name;
        LastName = usr.LastName;
    }
}

最佳答案

我认为做我想做的事情的最简单方法是实现 IValidatableObject :

public class Product : IValidatableObject
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (Prop1 < Prop2)
            yield return new ValidationResult("Property 1 can't be less than Property 2");
    }
}

另请参阅:Class-Level Model Validation with ... ASP.NET MVC 3

关于ASP.NET MVC 3 数据注释 : Add validation dynamically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6109277/

相关文章:

node.js - 根据用户输入动态地将国家/地区代码传递给@IsPhoneNumber()

javascript - jquery 验证插件 if 语句

asp.net-mvc-3 - 无法使用官方 C# 驱动程序将 BsonDocument 从 MVC3 序列化为 Json

asp.net - HttpUtility.UrlEncode() 可以防止开放重定向攻击吗?

c# - 这些列目前没有唯一值

c# - 当内容之间没有空格时 GridView 中的对齐问题

python - 在 python 中验证 yaml 文档

asp.net-mvc - 流利的验证不起作用的长度

mysql - C# Entity Framework : There is already an open DataReader associated with this Connection which must be closed first

asp.net - 使用 DBFactory 和 Oracle 存储过程 sys ref 游标返回数据集