Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何获取自定义mvc3属性以验证客户端_Javascript_Asp.net Mvc 3_Attributes_Customvalidator - Fatal编程技术网

Javascript 如何获取自定义mvc3属性以验证客户端

Javascript 如何获取自定义mvc3属性以验证客户端,javascript,asp.net-mvc-3,attributes,customvalidator,Javascript,Asp.net Mvc 3,Attributes,Customvalidator,我已经编写了一个自定义属性,但它在客户端似乎不起作用。它只在我调用ModelState.IsValid()方法时在服务器上工作。我在网上的某个地方读到,我需要在应用程序启动方法上注册自定义属性,但不清楚。请帮忙 public class MaximumAmountAttribute : ValidationAttribute { private static string defErrorMessage = "Amount available '$ {0:C}' can not

我已经编写了一个自定义属性,但它在客户端似乎不起作用。它只在我调用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;
    }
}

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

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

    需要保存错误消息的data val XXX属性
    Html.TextBoxFor
    也在做同样的事情(将这些属性添加到呈现的Html元素中)

  • 您必须通过以下方式创建和注册客户端验证:

    (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);
        });
    });
    

  • @bugarist-您好,您的解决方案正在运行,但我对验证消息有问题。我确实为属性提供了一条验证消息,但它说我得到的消息是“警告:没有为数量定义消息”。Amount是我正在验证的属性。请检查您是否在代码中使用与我上面显示的相同的验证规则名称。特别是检查这一行-
    options.messages['MaximumAmount']=options.message。检查我是否在所有地方都使用了相同的字符串“MaximumAmount”@bugarist,哇,谢谢你。我希望能请你喝一杯。我在选项上留下了“s”。消息[]。