不应该在下拉列表中触发JQuery Unobtrusive Validation

时间:2011-05-13 20:50:43

标签: jquery asp.net-mvc-3 jquery-validate unobtrusive-validation

我在使用viewmodels的.NET MVC3中有以下内容。我正在使用Razor和FluentValidation(但我也尝试过使用相同结果的DataAnnotations。)

从视图:

@Html.DropDownListFor(model=>model.L2, Model.RegisteredL2s, "[Select One]")

来自控制器:

    [HttpGet]
    [Authorize(Roles = "Supervisor")]
    public ActionResult Edit(string siteId, bool? isNew)
    {
            SiteEditViewModel model = new SiteEditViewModel();

                   List<SelectListItem> items = RegisteredL2Repository.GetRegisteredL2List()
                                                      .Select(x => new SelectListItem() { Text = x.L2, Value = x.L2.Trim() })
                                                      .OrderBy(x => x.Text)
                                                      .ToList();

                   model.RegisteredL2s = items.AsEnumerable();

                   if(!isNew.HasValue)
                   {
                        model.IsNew = false;
                   }

                   if(isNew.HasValue && (bool)isNew)
                   {
                        model.IsNew = true;
                        return View(model);
                   }

                   if(model.IsNew)
                   {
                        return View(model);
                   }

                   model.ConvertModelToViewModel(SiteRepository.GetSite(siteId));

                   return View("Edit", model);
              }
     }

来自ViewModel:

[DisplayName("Site:")]
          [TextboxLength(2)]
          public virtual string SiteId { get; set; }

          [DisplayName("L2:")]
          public virtual string L2 { get; set; }

          [DisplayName("Description:")]
          [TextboxLength(50)]
          public virtual string Description { get; set; }

          public IEnumerable<SelectListItem> RegisteredL2s { get; set; }

          public bool IsNew { get; set; }

          public string OverallError { get; set; }

来自我的Validator类(流利):

public SiteEditValidator()
          {
               RuleFor(model => model.SiteId)
                    .NotEmpty()
                    .WithMessage("Site is required.")
                    .Length(2)
                    .WithMessage("Site must be 2 characters. Ex: 1C")
                    .Matches(@"^[0-9A-Za-z]{2}$")
                    .WithMessage("Site contains invalid characters. Only letters and numbers.");

               RuleFor(model => model.L2)
                    .NotEmpty()
                    .WithMessage("L2 is required.")
                    .Length(2)
                    .WithMessage("L2 must be 2 characters. Ex: 30")
                    .Matches(@"^[\d]{2}$")
                    .WithMessage("L2 contains invalid characters. Only numbers are allowed.");

               RuleFor(model => model.Description)
                    .NotEmpty()
                    .WithMessage("Description is required.")
                    .Length(3, 50)
                    .WithMessage("Description must be at least 3 characters and not more than 50.")
                    .Matches(@"^[\w\,\.\'\-\s]{3,50}$")
                    .WithMessage("Description contains some invalid characters.");
          }

生成的HTML:

<div class="Edit-Field">
               <div class="Edit-Field-Label" style="width: 5em">
                    <label for="SiteId">Site:</label>
               </div>
               <div class="Editor-For">
                    <input autocomplete="off" data-val="true" data-val-length="Site must be 2 characters. Ex: 1C" data-val-length-max="2" data-val-length-min="2" data-val-regex="Site contains invalid characters. Only letters and numbers." data-val-regex-pattern="^[0-9A-Za-z]{2}$" data-val-required="Site is required." id="SiteId" maxlength="2" name="SiteId" readonly="readonly" style="width: 2.5em; background-color: LightGrey" type="text" value="30" />
                    <div class="Validation-For">
                         <span class="field-validation-valid" data-valmsg-for="SiteId" data-valmsg-replace="true"></span>
                    </div>
               </div>
          </div>
          <div class="Edit-Field">
               <div class="Edit-Field-Label" style="width: 5em">
                    <label for="L2">L2:</label>
               </div>
               <div class="Editor-For">
                    <select data-val="true" data-val-length="L2 must be 2 characters. Ex: 30" data-val-length-max="2" data-val-length-min="2" data-val-regex="L2 contains invalid characters. Only numbers are allowed." data-val-regex-pattern="^[\d]{2}$" data-val-required="L2 is required." id="L2" name="L2"><option value="">[Select One]</option>
<option value="30">30</option>
<option value="31">31</option>
<option value="32">32</option>
</select>
                    <div class="Validation-For">
                         <span class="field-validation-valid" data-valmsg-for="L2" data-valmsg-replace="true"></span>
                    </div>
               </div>
          </div>
          <div class="Edit-Field">
               <div class="Edit-Field-Label" style="width: 5em">
                    <label for="Description">Description:</label>
               </div>
               <div class="Editor-For">
                    <input autocomplete="off" data-val="true" data-val-length="Description must be at least 3 characters and not more than 50." data-val-length-max="50" data-val-length-min="3" data-val-regex="Description contains some invalid characters." data-val-regex-pattern="^[\w\,\.\&#39;\-\s]{3,50}$" data-val-required="Description is required." id="Description" maxlength="50" name="Description" style="width: 30em" type="text" value="Central Office-Cash Receipts Unit" />
                    <div class="Validation-For">
                         <span class="field-validation-valid" data-valmsg-for="Description" data-valmsg-replace="true"></span>
                    </div>
               </div>
          </div>

现在出现问题:

我从预先填充的IEnumerable(RegisteredL2s)中获取了L2字段,并将其作为下拉列表(ID = L2,大致位于html的中间)。 L2是必需的,必须具有一定的长度(2)。我的问题是,即使用户选择了[选择一个]以外的其他内容,也会出现长度错误。如果我删除该错误,则会出现正则表达式错误。提交时服务器端验证工作正常。为什么要这样做,我该如何制止呢?或者我可以关闭这个领域的客户端吗?

更新 我相信我发现了jquery.validate.js的问题......我希望有人来证实这一点。

以下是我更改的原始代码行,似乎解决了我的问题: 这是第683行。第686行是问题所在。

getLength: function(value, element) {
  switch( element.nodeName.toLowerCase() ) {
    case 'select':

        return $("option:selected", element).length;            case 'input':
        if( this.checkable( element) )
        return this.findByName(element.name).filter(':checked').length;
        }
    return value.length;
    },

我相信当你有一个长度验证器所需的下拉值时,它会产生错误。当我运行我的代码时,该行的长度返回1而不是2.如果我将粗体线更改为return $("option:selected", element).val().length;,它将正常运行。如果这是一个正确的错误,如果我的修复程序不会干扰jquery.validation的任何其他部分,那么任何评论都会有所帮助。

这是来自jquery.validation 1.8.1(自从我认为我的版本可能不同步以来从1.7更新)Jquery = 1.6.1。

更新2: 不确定这是否应该是一个确切的答案,但是:

事实证明,根据rangeQ的JQuery.Validation文档(这是jquery.validation.unobtrusive构造的长度正好为2)here它表明对于选择(下拉列表)它是为了确保已选择某些数量的项目,而不是用于验证值的长度。

我正在检查值长度或在客户端为这个特定项目关闭验证,同时保留验证服务器端。

1 个答案:

答案 0 :(得分:1)

这不是一个完整的答案(我不确定如何在DataAnnotations下完成同样的事情),这就是为什么我没有将它标记为已接受的答案。

在FluentValidation下,我更改了上面的以下行

RuleFor(model => model.L2)                     
     .NotEmpty()                     
     .WithMessage("L2 is required.")                     
     .Length(2)                     
     .WithMessage("L2 must be 2 characters. Ex: 30")                     
     .Matches(@"^[\d]{2}$")                     
     .WithMessage("L2 contains invalid characters. Only numbers are allowed.");

要:

RuleFor(model => model.L2)
                .NotEmpty()
                .WithMessage("L2 is required.")
                .Length(2)
                .When(x => 1==1)
                .WithMessage("L2 must be 2 characters. Ex: 30")
                .Matches(@"^[\d]{2}$")
                .WithMessage("L2 contains invalid characters or is too long. Only numbers are allowed.");

这有效地关闭了客户端验证,但保留了服务器端。显然,Fluent不会为具有When条件的项目生成客户端验证。希望这可以帮助那些人。