你能在Asp MVC 2.0中添加动态验证属性吗?

时间:2010-07-15 06:00:18

标签: validation asp.net-mvc-2

我意识到我可以简单地将[Required]属性添加到类属性中,MVC将自动以非常好的方式进行验证。

然而,我想要做的是在运行时分配属性,这可能吗?

例如,说我有

public class Cert {       
  public string MedicalNum { get; set; }

  public int Certified { get; set; }

...
}

我想将MedicalNum属性[必需](因此在视图中正确验证)如果认证属性设置为1。

这可能吗?

1 个答案:

答案 0 :(得分:1)

看看这个post on SO。基本上,采用示例propertiesMustMatch验证来了解如何使用具有多个属性的数据注释。这是对你的新代码可能的快速刺戳(注意,在cap,semis上可能不是100%语法正确)

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class RequiredMedicalNum: ValidationAttribute
{
    private const string _defaultErrorMessage = "{0} is required when certified is true";

    private readonly object _typeId = new object();

public RequiredMedicalNum(string medicalNum, string Certified)
    : base(_defaultErrorMessage)
{
    _medicalNum = medicalNum;
    _certified= Certified;
}

public string _medicalNum 
{
    get;
    private set;
}

public string _certified
{
    get;
    private set;
}

public override object TypeId
{
    get
    {
        return _typeId;
    }
}

public override string FormatErrorMessage(string name)
{
    return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
        _medicalNum, _certified);
}

public override bool IsValid(object value)
{
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
    object medicalNum = properties.Find(_medicalNum, true /* ignoreCase */).GetValue(value);
    object certified= properties.Find(_certified, true /* ignoreCase */).GetValue(value);
    if(certified == 1){
        Return String.IsNullOrEmpty(medicalNum);  
    }
}
}