自定义验证属性不在客户端工作

时间:2014-07-07 16:09:23

标签: c# asp.net jquery-validate asp.net-mvc-5 unobtrusive-validation

根据这个postone我试图实现超过逻辑的自定义验证。

所以我有以下代码:

 public class DynamicRangeGreaterThenValidator : ValidationAttribute, IClientValidatable
 {
        private readonly string _minPropertyName;

        public DynamicRangeGreaterThenValidator(string minPropertyName)
        {
            _minPropertyName = minPropertyName;
        }

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

            if (minProperty == null)
            {
                return new ValidationResult(string.Format("Unknown property {0}", _minPropertyName));
            }

            var minValue = (double)minProperty.GetValue(validationContext.ObjectInstance, null);
            var currentValue = (double)value;

            if (currentValue <= minValue)
            {
                return new ValidationResult(
                    string.Format(
                        ErrorMessage,
                        minValue
                        )
                    );
            }

            return null;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,
            ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ValidationType = "greaterthen",
                ErrorMessage = this.ErrorMessage,
            };
            rule.ValidationParameters["minvalueproperty"] = _minPropertyName;
            yield return rule;
        }
    }

JavaScript的:

jQuery(document).ready(function () {
    jQuery.validator.unobtrusive.adapters.add(
        'greaterthen',
        ['minvalueproperty'],
        function(options) {
            // simply pass the options.params here
            options.rules['greaterthen'] = options.params;
            options.messages['greaterthen'] = options.message;
        }
    );

    jQuery.validator.addMethod('greaterthen', function(value, element, params) {
        var minValue = parseFloat(jQuery('input[name="' + params.minvalueproperty + '"]').val(), 10);
        var currentValue = parseInt(value, 10);
        if (isNaN(minValue) || isNaN(currentValue) || minValue >= currentValue) {
            var message = jQuery(element).attr('data-val-greaterthen');
            jQuery.validator.messages.greaterthen = jQuery.format(message, minValue);
            return false;
        }
        return true;
    }, '');
});

我的模特:

public class TestModel
{   
   [Required(ErrorMessageResourceType = typeof (Resource), ErrorMessageResourceName = "RequiredParameter")]
   /*   [Display(Name = "MinQuantity", ResourceType = typeof (Resource))]*/
   public double MinQuantity { get; set; }

   [Required(ErrorMessageResourceType = typeof (Resource), ErrorMessageResourceName = "RequiredParameter")]
   public double MaxQuantity { get; set; }

   [Required(ErrorMessageResourceType = typeof (Resource), ErrorMessageResourceName = "RequiredParameter")]
   [Display(Name = "NormalQuantity", ResourceType = typeof (Resource))]
   [DynamicRangeGreaterThenValidator("MinQuantity", ErrorMessage = "Value must be greater than {0}")]
   public double NormalQuantity { get; set; }
}

不幸的是,此代码仅适用于服务器端,我无法使此代码适用于客户端。

我的问题是我没有找到任何创建客户端验证的规则。我现在不应该知道适配器和方法的名称。请帮助我使用此代码,如果可以解释客户端验证应该如何工作。

感谢。

0 个答案:

没有答案