MVC DropDownListFor and StringLength Attribute Doesn't Play Well Together

My string length check always fails with dropdownlists with a string value.

Here is my model:

[Required(ErrorMessage = "Required")]
[StringLength(2, MinimumLength = 2)]
[Display(Name = "Home Address State")]
public string HomeAddressState { get; set; }

Here is my view:

@Html.DropDownListFor(model => model.HomeAddressState, new SelectList(ViewBag.States, "Value", "Text"), string.Empty)
@Html.ValidationMessageFor(model => model.HomeAddressState)

Here is the html output:

<select data-val="true" data-val-length="The field Home Address State must be a string with a minimum length of 2 and a maximum length of 2." data-val-length-max="2" data-val-length-min="2" data-val-required="Required" id="HomeAddressState" name="HomeAddressState"><option value=""></option>
<option value="CA">California</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="OH">Ohio</option>
</select>

No matter which option is selected, StringLength string checking is not performed on the client side. What am I doing wrong?

+5
source share
3 answers

Here's the corresponding jquery validation code. As you can see, it seems that the length check applies to the number of options selected, and not to the length of the parameter. They seem to apply only to multibyte lists. Some kind of strange, to be honest.

maxlength: function(value, element, param) {
    return this.optional(element) || this.getLength($.trim(value), element) <= param;
}

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

, getLength, value.length .

$.validator.prototype.getLength = function (value, element) {
    return value.length;
}
+6

, :

$.validator.prototype.getLength = function (value, element) {
    switch (element.nodeName.toLowerCase()) {
        case 'select':
            {
                var attr = $(this).attr('multiple');
                // For some browsers, `attr` is undefined; for others,
                // `attr` is false.  Check for both.
                if (typeof attr !== 'undefined' && attr !== false) {
                    return $("option:selected", element).length;
                }
            }
        case 'input':
            if (this.checkable(element))
                return this.findByName(element.name).filter(':checked').length;
    }
    return value.length;
}

: DropDownFor, ....

+2

StringLength rangelength jquery.validate. , , , 1,

0

All Articles