繁体   English   中英

ASP.NET MVC。 如何根据参数禁用所需的验证?

[英]ASP.NET MVC. How disable required validation based on a parameter?

我有一个实体类,根据选择器具有一些必需的属性。

例如:选择器可以采用“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;}

}

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

客户端验证已经解决。

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

您可以创建自己的自定义验证属性,也可以使用MVC Foolproof验证 ,然后执行以下操作:

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

 }

正如Win所提到的,它似乎暂时没有处于活动开发状态,所以你可能想要创建自己的自定义验证属性,这需要更多的工作,但你可以更好地控制验证本身。 根据您的需求选择。

对于自定义验证属性,您可以执行以下操作:

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")]

我相信mvcfoolproof将适用于这种情况[ https://foolproof.codeplex.com/][1]它也可以在nuget上使用。 它添加了额外的验证属性,例如

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

它使用起来非常简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM