1

我正在使用 MVC 中的自定义验证来验证基于另一个字段的字段,我遇到了这个实现:

 public class RequiredIfAttribute : ValidationAttribute
    {
        private String PropertyName { get; set; }
        private String ErrorMessage { get; set; }
        private Object DesiredValue { get; set; }

        public RequiredIfAttribute(String propertyName, Object desiredvalue, String errormessage)
        {
            this.PropertyName = propertyName;
            this.DesiredValue = desiredvalue;
            this.ErrorMessage = errormessage;
        }

        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            Object instance = context.ObjectInstance;
            Type type = instance.GetType();
            Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
            if (proprtyvalue.ToString() == DesiredValue.ToString())
            {
                return new ValidationResult(ErrorMessage);
            }
            return ValidationResult.Success;
        }
    }

我有一个简单的类定义如下:

public class Person
{
    public int PersonID { get; set; }
    public string name { set; get; }
    [RequiredIf("name","","Address is required")]
    public string addr { get; set; }
}

当我运行该页面时,我收到一个Object reference not set to an instance of an object.错误,但更改该行以[RequiredIf("name","John","Address is required")]产生预期的结果。我的问题是,您如何使用它来检查该字段是否为空。

我也尝试将行更改为,[RequiredIf("name",null,"Address is required")]但我得到了同样的错误。

4

2 回答 2

2

这似乎有效:

protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            if (value != null) { return ValidationResult.Success; }

            Object instance = context.ObjectInstance;
            Type type = instance.GetType();
            Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
            if (proprtyvalue == null) {
               return new ValidationResult(ErrorMessage);
            }
            return ValidationResult.Success;
        }
于 2013-02-22T21:38:54.207 回答
0

您没有发布您正在测试的实际 Person 实例,所以我只是猜测:在尝试调用 ToString() 之前确保PropertyName的属性值不为空。所以你的Person.Name不能为null

于 2013-02-22T20:12:59.110 回答