1

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

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


 public byte Type { get; set; }

如果 Type==3,我想收到必需的消息。

4

2 回答 2

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;
        }
    }
于 2012-07-16T10:55:54.387 回答
0

看看下面的问题:

使用数据注释的依赖属性的自定义模型验证

快速浏览:

[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; }
}
于 2012-07-16T10:07:47.393 回答