繁体   English   中英

如何在客户端验证中验证二变量规则?

[英]How can I validate two-variable rules in client-side validation?

我有以下poco:

public class CabinetItem
{
    [Required]
    [Display(...)]
    public double Width { get; set; }

    public double MinWidth { get; }
}

我要弄清楚的是,当MinWidth可以是任何值时,如何验证Width大于MinWidth 最小宽度是取决于橱柜项目的约束。 注意:我也MaxWidth了一个MaxWidth来简化这个问题。

选项1:

万无一失的 nuget软件包在您的情况下可能非常有用。

安装万无一失的 nuget软件包,并使用其额外有用的属性,如下所示:

public class CabinetItem
{
    [Required]
    [Display(...)]
    [GreaterThan("MinWidth")]
    public double Width { get; set; }

    public double MinWidth { get; }
}

还有其他功能:

  • [是]
  • [等于]
  • [不等于]
  • [比...更棒]
  • [少于]
  • [GreaterThanOrEqualTo]
  • [LessThanOrEqualTo]

资源: 是否可以通过数据注释来验证一个日期属性是否大于或等于另一个日期属性?

您可以创建一个CustomValidationAttribute

以这个为例:

    public class GreaterThanAttribute : ValidationAttribute, IClientValidatable
    {
        private readonly string _testedPropertyName;
        private readonly bool _allowEqualValues;
        private readonly string _testedPropertyDisplayName;

        public override string FormatErrorMessage(string displayName)
        {
            return string.Format(ErrorMessages.GreaterThan_Message, displayName, _testedPropertyDisplayName);
        }

        public GreaterThanAttribute(string testedPropertyName, Type resourceType, string testedPropertyDisplayNameKey, bool allowEqualValues = false)
        {
            _testedPropertyName = testedPropertyName;
            _allowEqualValues = allowEqualValues;
            var rm = new ResourceManager(resourceType);
            _testedPropertyDisplayName = rm.GetString(testedPropertyDisplayNameKey);            
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var propertyTestedInfo = validationContext.ObjectType.GetProperty(_testedPropertyName);

            if (propertyTestedInfo == null)
            {
                return new ValidationResult(string.Format("unknown property {0}", _testedPropertyName));
            }

            var propertyTestedValue = propertyTestedInfo.GetValue(validationContext.ObjectInstance, null);

            if (value == null || !(value is Decimal))
            {
                return ValidationResult.Success;
            }

            if (propertyTestedValue == null || !(propertyTestedValue is Decimal))
            {
                return ValidationResult.Success;
            }

            // Compare values
            if ((Decimal)value >= (Decimal)propertyTestedValue)
            {
                if (_allowEqualValues && value == propertyTestedValue)
                {
                    return ValidationResult.Success;
                }
                else if ((Decimal)value > (Decimal)propertyTestedValue)
                {
                    return ValidationResult.Success;
                }
            }

            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = FormatErrorMessage(metadata.DisplayName),
                ValidationType = "greaterthan"
            };
            rule.ValidationParameters["propertytested"] = _testedPropertyName;
            rule.ValidationParameters["allowequalvalues"] = _allowEqualValues;
            yield return rule;
        }
    }

您可以像这样使用它:

public Decimal MyProperty1 { get; set; }

[GreaterThanAttribute("MyProperty1", typeof(Strings), "Error_String")]
public Decimal MyProperty2 { get; set; }

[GreaterThanAttribute("MyProperty2", typeof(Strings), "Error_String")]
public Decimal MyProperty3 { get; set; }

在客户端,您可以添加以下内容以进行客户端验证:

jQuery.validator.unobtrusive.adapters.add('greaterthan', ['propertytested', 'allowequalvalues'], function (options) {
            options.params["allowequalvalues"] = options.params["allowequalvalues"] === "True" ||
                                                 options.params["allowequalvalues"] === "true" ||
                                                 options.params["allowequalvalues"] === true ? true : false;

            options.rules['greaterthan'] = options.params;
            options.messages['greaterthan'] = options.message;
        });
jQuery.validator.addMethod("greaterthan", function (value, element, params) {        
            var properyTestedvalue= $('input[name="' + params.propertytested + '"]').val();
            if (!value || !properyTestedvalue) return true;
            return (params.allowequalvalues) ? parseFloat(properyTestedvalue) <= parseFloat(value) : parseFloat(properyTestedvalue) < parseFloat(value);
        }, ''); 

暂无
暂无

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

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