2

我需要实现一个RequiredIF 验证器,它依赖于两个值,一个复选框和一个从下拉列表中选择的值。如果可能的话,我需要类似的东西

  [RequiredIf("Property1", true,"Property2,"value", ErrorMessageResourceName = "ReqField", ErrorMessageResourceType = typeof(RegisterUser))]
4

2 回答 2

2

这是创建您自己的RequiredIf 和RequiredIfNot 自定义验证器的代码。如果要检查 2 个值,只需添加附加代码。

必填

public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
    private readonly RequiredAttribute _innerAttribute = new RequiredAttribute();

    internal string _dependentProperty;
    internal object _targetValue;

    public RequiredIfAttribute(string dependentProperty, object targetValue)
    {
        _dependentProperty = dependentProperty;
        _targetValue = targetValue;
    }

    /// <summary>
    /// Returns if the given validation result is valid. It checks if the RequiredIfAttribute needs to be validated
    /// </summary>
    /// <param name="value">Value of the control</param>
    /// <param name="validationContext">Validation context</param>
    /// <returns></returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var field = validationContext.ObjectType.GetProperty(_dependentProperty);
        if (field != null)
        {
            var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
            if ((dependentValue == null && _targetValue == null) || (dependentValue.ToString() == _targetValue.ToString()))
            {
                if (!_innerAttribute.IsValid(value))
                {
                    return new ValidationResult(ErrorMessage);
                }
            }
            return ValidationResult.Success;
        }
        else
        {
            throw new ValidationException("RequiredIf Dependant Property " + _dependentProperty + " does not exist");
        }
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = ErrorMessageString,
            ValidationType = "requiredif",
        };
        rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(_dependentProperty);
        rule.ValidationParameters["desiredvalue"] = _targetValue is bool ? _targetValue.ToString().ToLower() : _targetValue;

        yield return rule;
    }
}

要求如果不是:

public class RequiredIfNotAttribute : ValidationAttribute, IClientValidatable
{
    private readonly RequiredAttribute _innerAttribute = new RequiredAttribute();

    internal string _dependentProperty;
    internal object _targetValue;

    public RequiredIfNotAttribute(string dependentProperty, object targetValue)
    {
        _dependentProperty = dependentProperty;
        _targetValue = targetValue;
    }

    /// <summary>
    /// Returns if the given validation result is valid. It checks if the RequiredIfAttribute needs to be validated
    /// </summary>
    /// <param name="value">Value of the control</param>
    /// <param name="validationContext">Validation context</param>
    /// <returns></returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var field = validationContext.ObjectType.GetProperty(_dependentProperty);
        if (field != null)
        {
            var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
            if ((dependentValue == null && _targetValue == null) || (dependentValue.ToString() != _targetValue.ToString()))
            {
                if (!_innerAttribute.IsValid(value))
                {
                    return new ValidationResult(ErrorMessage);
                }
            }
            return ValidationResult.Success;
        }
        else
        {
            throw new ValidationException("RequiredIfNot Dependant Property " + _dependentProperty + " does not exist");
        }
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = ErrorMessageString,
            ValidationType = "requiredifnot",
        };
        rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(_dependentProperty);
        rule.ValidationParameters["desiredvalue"] = _targetValue is bool ? _targetValue.ToString().ToLower() : _targetValue;

        yield return rule;
    }
}

用法: 在您的模型中使用以下 DataAnnotation。

[RequiredIf("IsRequired", true, ErrorMessage = "First Name is required.")]
于 2019-10-16T20:24:18.893 回答
1

您必须制作自定义验证器。这是实现这一目标的最佳方式。我希望这有助于自定义验证器

于 2016-01-06T07:38:38.773 回答