根据另一个属性验证

时间:2012-07-16 09:58:17

标签: asp.net asp.net-mvc-3 validation

如何验证某个字段的验证是否依赖于另一个字段?

 [Required if Type==3]
 public long RID2 { get; set; }


 public byte Type { get; set; }

如果Type == 3,我想获得必需的消息。

2 个答案:

答案 0 :(得分:0)

看一下以下问题:

Custom model validation of dependent properties using Data Annotations

快速浏览一下:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class PropertiesMustMatchAttribute : ValidationAttribute
{
   public override bool IsValid(object value)
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
        object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
        object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
        // place here your valdiation
        return Object.Equals(originalValue, confirmValue);
    }
}

用法:

[PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public class ChangePasswordModel
{
    public string NewPassword { get; set; }
    public string ConfirmPassword { get; set; }
}

答案 1 :(得分:0)

为您编写了属性。如果你愿意,可以稍微重构,但想法如下。

使用:

[RequiredIfTypeIs("Type", 3)]
public long RID2 { get; set; }

public byte Type { get; set; }

属性的测试:

[TestFixture]
public class RequiredIfTypeIsAttributeTests
{
    private class YourModel
    {
        [RequiredIfTypeIs("Type", 3)]
        public long RID2 { get; set; }

        public byte Type { get; set; }

    }

    private class TestRequiredIfTypeIsAttribute : RequiredIfTypeIsAttribute
    {
        public TestRequiredIfTypeIsAttribute(string typePropertyName, byte requiredTypePropertyValue)
            : base(typePropertyName, requiredTypePropertyValue)
        {
        }

        public ValidationResult TestIsValid(object value, ValidationContext validationContext)
        {
            return IsValid(value, validationContext);
        }
    }

    [Test]
    public void TypeIs3_RidIs0__Return_IsNotValid()
    {
        var yourModel = new YourModel()
        {
            RID2 = 0,
            Type = 3,
        };

        TestValidationWithModel(yourModel, false);
    }

    [Test]
    public void TypeIs2_RidIs0__Return_IsValid()
    {
        var yourModel = new YourModel()
        {
            RID2 = 0,
            Type = 2,
        };

        TestValidationWithModel(yourModel, true);
    }

    [Test]
    public void TypeIs3_RidIs1__Return_IsValid()
    {
        var yourModel = new YourModel()
        {
            RID2 = 1,
            Type = 3,
        };

        TestValidationWithModel(yourModel, true);
    } 

    private void TestValidationWithModel(YourModel yourModel, bool success)
    {
        var validationContext = new ValidationContext(yourModel, null, null);
        var attribute = new TestRequiredIfTypeIsAttribute("Type", 3);
        var result = attribute.TestIsValid(yourModel.RID2, validationContext);

        Assert.AreEqual(success, result == ValidationResult.Success);
    }
}

属性类:

public class RequiredIfTypeIsAttribute : ValidationAttribute
    {
        private string _typePropertyName;
        private byte _requiredTypePropertyValue;

        public RequiredIfTypeIsAttribute(string typePropertyName, byte requiredTypePropertyValue) : base()
        {
            _typePropertyName = typePropertyName;
            _requiredTypePropertyValue = requiredTypePropertyValue;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var comparedPropertyInfo = validationContext.ObjectType.GetProperty(_typePropertyName);

            var propertyValue = (byte) comparedPropertyInfo.GetValue(validationContext.ObjectInstance, null);

            bool valid = true;

            if (propertyValue == _requiredTypePropertyValue)
            {
                valid = false;

                int checkedValue;

                if (int.TryParse(value.ToString(), out checkedValue))
                {
                    if (checkedValue > 0)
                    {
                        valid = true;
                    }
                }
            }


            if (!valid)
            {
                var message = base.ErrorMessage;
                return new ValidationResult(message);
            }
            return null;
        }
    }