2016-07-29 57 views
1

我确实有一个实体类,具有一些必要的属性,具体取决于选择器。ASP.NET MVC。如何根据参数禁用所需的验证?

例如:选择器可以采用“1”或“2”。如果选择器为“1”,则需要一组参数。如果选择器是“2”,则需要另一组参数。

class MyClass{ 

    public int Selector {get;set;} // 1 or 2 

    public string A_required_for_1 {get;set;} 
    public string B_required_for_1 {get;set;} 

    public string C_required_for_2 {get;set;} 
    public string D_required_for_2 {get;set;} 

    public string E_Required_for_both_selectors {get;set;} 

} 

用户应该能够在视图中创建或编辑操作期间在选择器之间切换。

客户端验证已经解决。

如何在服务器验证中处理它?

+0

这是‘在某些情况下禁用需要确认属性’不是复制 –

+1

请你帮个忙和独立的编辑和你的应用程序中创建功能。 – Programmer

+0

@NicholasKinney我不明白你为什么评论适用于这个问题。你能澄清一下吗? –

回答

2

您可以创建自己的自定义验证属性或使用MVC Foolproof Validation然后执行:

class MyClass 
{ 

    public int Selector {get;set;} // 1 or 2 

    [RequiredIf("Selector == 1", ErrorMessage = "Your Error Message")] 
    public string A_required_for_1 {get;set;} 

    [RequiredIf("Selector == 1", ErrorMessage = "Your Error Message")] 
    public string B_required_for_1 {get;set;} 

    [RequiredIf("Selector == 2", ErrorMessage = "Your Error Message")] 
    public string C_required_for_2 {get;set;} 

    [RequiredIf("Selector == 2", ErrorMessage = "Your Error Message")] 
    public string D_required_for_2 {get;set;} 

    [Required("Your Error Message")] 
    public string E_Required_for_both_selectors {get;set;} 

} 

似乎正如赢提到不一直在积极发展了一段时间,所以你可能会想要去沿着创建自己的自定义验证属性的路线,这需要更多的工作,但您可以更好地控制验证本身。根据您的需要选择。

对于一个自定义的验证属性,你可以做这样的事情:

public class RequiredIfOtherProperty : ValidationAttribute 
{ 
    private readonly string _otherPropertyName; 
    private readonly string _compareValue; 

    public RequiredIfOtherProperty(string otherPropertyName, string compareValue) 
    { 
     _otherPropertyName = otherPropertyName; 
     _compareValue = compareValue; 
    } 

    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     var otherProperty = validationContext.ObjectType.GetProperty(_otherPropertyName); 
     if (otherProperty == null) 
     { 
      return new ValidationResult($"Property '{_otherPropertyName}' does not exist"); 
     ); 
    } 

    var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null); 
    if (!_compareValue.Equals(otherPropertyValue)) 
    { 
     return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName)); 
    } 

    return null; 
} 

应该给你,你可以做一个粗略的想法,你可以改变实际的验证,但是你喜欢。然后,您可以像使用普通属性一样使用它。

[RequiredIfOtherProperty("SomeProperty", "ValueToCompareWith")] 
+1

不错的图书馆,但它是***贝塔*** 0.9。 4517,并且自2012年5月14日起未更新。 – Win

+0

不错的建议@Win –

+0

“自定义验证属性”是什么意思? –

1

我相信mvcfoolproof会适合这种情况[https://foolproof.codeplex.com/][1] 它也可以在nuget上找到。它增加了额外的验证属性,如

[RequiredIf] 
[RequiredIfNot] 
[RequiredIfTrue] 
[RequiredIfFalse] 
[RequiredIfEmpty] 
[RequiredIfNotEmpty] 
[RequiredIfRegExMatch] 
[RequiredIfNotRegExMatch] 

这是非常简单的使用。

+1

不错的图书馆,但它是***贝塔*** 0.9.4517,并且自2012年5月14日以来一直未更新。 – Win

+0

不错的建议@Win –