簡體   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