2012-07-16 189 views
1

如何驗證一個字段的驗證是否取決於另一個字段?驗證取決於另一個屬性

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


public byte Type { get; set; } 

我想獲得必要的消息,如果類型== 3。

+0

http://stackoverflow.com/questions/7136515/conditional -validation-on-mvc3-model-class – 2012-07-16 10:03:31

+0

這很容易,看看下面的問題: http://stackoverflow.com/q/2280539/1268570 – Jupaol 2012-07-16 10:05:51

+0

有關RequiredIf屬性的問題 - http://stackoverflow.com/questions/3713281/attribute-dependent-on-another-field – 2012-07-16 10:11:24

回答

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; } 
} 
+0

我有一個簡單的問題。要獲取屬性值我不能直接通過將傳遞的對象轉換爲ChangePasswordModel? – VJAI 2012-07-16 10:48:00

+0

嗯,你可以,但驗證者的想法是使其通用 – Jupaol 2012-07-16 20:40:07

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; 
     } 
    } 
相關問題