实现RequiredIf和RequiredIfNot属性验证器,它取决于两个值

时间:2012-10-24 23:40:14

标签: asp.net-mvc-3

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

这样的东西
  [RequiredIf("Property1", true,"Property2,"value", ErrorMessageResourceName = "ReqField", ErrorMessageResourceType = typeof(RegisterUser))]

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

以下是用于创建您自己的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;
    }
}

RequireIfNot:

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