为什么使用自定义数据注释属性进行不显眼的客户端验证不起作用?

时间:2014-05-12 16:54:49

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

我已创建了用于检查选择了多少选项的简单属性。 我在js中添加了适配器和验证方法,但验证仍然无效。

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace MicroSpecShow.WebAdmin.AdminCore.Attributes
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    sealed public class AtLeastChecked : ValidationAttribute, IClientValidatable
    {
        public int Min { get; set; }

        public AtLeastChecked(int min)
        {
            Min = min;
        }


        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var list = value as ICollection;
            string message;
            if (list != null)
            {
                var count = list.Count;
                if (count < Min)
                {
                    message = string.Format(ErrorMessageString, Min);
                    return new ValidationResult(message);
                }
            }
            return ValidationResult.Success;

        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = ErrorMessageString;
            rule.ValidationType = "atleastchecked";
            rule.ValidationParameters.Add("min", Min);

            yield return rule;
        }
    }
}

我的js

<script type="text/javascript">
        $(function () {
            ShowGeneral.init();

        });
        (function (jQuery) {
            console.log(jQuery);
            jQuery.validator.unobtrusive.adapters.add('atleastchecked', ['min'], function (options) {
                options.rules['atleastchecked'] = options.params.min;
                options.messages['atleastchecked'] = options.message;
            });
            jQuery.validator.addMethod('atleastchecked', function (value, element, min) {
                if (typeof $(element).val() === 'undefined' || $(element).val() === null) {
                    return false;
                }
                if ($(element).val().length < min) {
                    return false;
                }
                return true;
            }, '');
        })($);

    </script>

剃刀:

 <div class="col-md-6">
                    @Html.ListBoxFor(m => m.SelectedAllowedLanguages, Model.AllLanguages, new { multiple = "multiple", @class = "show-general-form-control" })
</div>

生成的HTML结构:

<div class="col-md-6">
   <select class="show-general-form-control" data-val="true" data-val-atleastchecked="You must check at least {0} language." data-val-atleastchecked-min="2" id="SelectedAllowedLanguages" multiple="multiple" name="SelectedAllowedLanguages" style="display: none;">
      <option selected="selected" value="1">English</option>
      <option selected="selected" value="2">French</option>
   </select>
   <button type="button" class="ui-multiselect ui-widget ui-state-default ui-corner-all" aria-haspopup="true" style="width: 516px;"><span class="ui-icon ui-icon-triangle-2-n-s"></span><span>2 selected</span></button>
</div>

我的应用设置:

<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

为什么验证不起作用以及如何解决这个问题?

0 个答案:

没有答案