Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Unobtrusive Validation firing on dropdownlist when it should not

I have the following in an .NET MVC3 using viewmodels. I am using Razor and FluentValidation (but I have also tried DataAnnotations with the same results).

From View:

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

From Controller:

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

From 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; }

From my Validator class (Fluent):

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.");
          }

And the generated 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>

Now the problem:

I have the L2 field being drawn from a prepopulated IEnumerable (RegisteredL2s) and having that as a dropdownlist (ID=L2, roughly middle of the html). L2 is required and must be of a certain length (2). My problem is that even when a user has picked something other than the [Select One] the length error appears. If I remove that error the Regular Expression error appears. Server-side validation on submit works correctly. Why is it doing this and how do I stop it? Or can I just turn off the client-side for this one field?

Update: I believe I found an issue with jquery.validate.js... I would like someone to confirm this.

Here is the original lines of code that I changed that seems to have fixed my problem: this is line 683. Line 686 is the problem point.

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;
    },

I believe that when you have a required dropdown value with the length validator also present, it generates the error. When I run my code the length of this line returns 1 not 2. If I change the bolded line to return $("option:selected", element).val().length; it functions properly. Any comments on if this is a proper bug and if my fix will not interfere with any other part of jquery.validation would be helpful.

This is from jquery.validation 1.8.1 (updated from 1.7 since I thought my versions may have been out of sync) Jquery = 1.6.1.

Update 2: Not sure if this should be an exact answer but:

It turns out that according to the JQuery.Validation documentation for rangelength (which is what jquery.validation.unobtrusive constructs for a Length of exactly 2) here It states that for selects (dropdownlist) it is for ensuring that a certain number items has been selected not for verifying the length of the value.

I am after checking the value length or turning validation off on the client side for this particular item while retaining validation server-side.

like image 865
Richard H Avatar asked Nov 13 '22 23:11

Richard H


1 Answers

It's not a complete answer(I am not sure how to accomplish the same thing under DataAnnotations) which is why I have not marked it as the accepted answer.

Under FluentValidation I changed the following line above

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.");

To:

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.");

This effectively turned off clientside validation but left the serverside intact. Apparently Fluent doesn't generate client-side validation for items with When conditions. Hopefully this helps someone out there.

like image 172
Richard H Avatar answered Dec 10 '22 23:12

Richard H