1

我已经编写了一个自定义属性,但它似乎不适用于客户端。它仅在我调用 ModelState.IsValid() 方法时在服务器上有效。我在网上某处读到我需要在应用程序启动方法上注册自定义属性,但不清楚。请帮忙。

public class MaximumAmountAttribute : ValidationAttribute
    {
    private static string defErrorMessage = "Amount available '$ {0:C}' can not be more than loan amount '$ {1:C}'";
    private string MaximumAmountProperty { get; set; }
    double minimumValue = 0;
    double maximumValue = 0;

    public MaximumAmountAttribute(string maxAmount)
        : base(defErrorMessage)
    {
        if (string.IsNullOrEmpty(maxAmount))
            throw new ArgumentNullException("maxAmount");

        MaximumAmountProperty = maxAmount;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            PropertyInfo otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(MaximumAmountProperty);

            if (otherPropertyInfo == null)
            {
                return new ValidationResult(string.Format("Property '{0}' is undefined.", MaximumAmountProperty));
            }

            var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);

            if (otherPropertyValue != null && !string.IsNullOrEmpty(otherPropertyValue.ToString()))
            {
                minimumValue = Convert.ToDouble(value);
                maximumValue = Convert.ToDouble(otherPropertyValue);

                if (minimumValue > Convert.ToDouble(otherPropertyValue.ToString()))
                {
                    return new ValidationResult(string.Format(defErrorMessage, minimumValue, maximumValue));
                }
            }
        }

        return ValidationResult.Success;
    }
}
4

1 回答 1

2

使用自定义验证属性创建服务器端验证不会将验证规则“传输”到客户端浏览器(呈现自定义 javascript 验证函数)。
您也必须将验证逻辑编写为客户端脚本。您必须做一些事情:

  1. 确保必须在客户端验证的元素(输入)如下所示:

    <input data-val-MaximumAmount="Validation error massage" />

    需要包含错误消息的 data-val-XXX 属性。Html.TextBoxFor正在做同样的事情(将此类属性添加到呈现的 html 元素中)。

  2. 您必须以这种方式创建和注册客户端验证:

    (function ($) {
        // Creating the validation method
        $.validator.addMethod('MaximumAmount', function (value, element, param) {
            if (...) // some rule. HERE THE VALIDATION LOGIC MUST BE IMPLEMENTED!
                return false;
            else
                return true;
        });
    
        // Registering the adapter
        $.validator.unobtrusive.adapters.add('MaximumAmount', function (options) {
            var element = options.element,
                message = options.message;
    
            options.rules['MaximumAmount'] = $(element).attr('data-val-MaximumAmount');
            if (options.message) {
                options.messages['MaximumAmount'] = options.message;
            }
        });
    
    })(jQuery);
    
    // Binding elements to validators
    $(function () {
        $(':input[data-val-MaximumAmount]').each(function () {
            $.validator.unobtrusive.parseElement(this, true);
        });
    });
    
于 2013-03-27T12:13:54.693 回答