我的stringlength验证总是在具有字符串值的下拉列表中失败.
这是我的模型:
[required(ErrorMessage = "required")] [StringLength(2,MinimumLength = 2)] [Display(Name = "Home Address State")] public string HomeAddressState { get; set; }
这是我的观点:
@Html.DropDownListFor(model => model.HomeAddressState,new SelectList(ViewBag.States,"Value","Text"),string.Empty) @Html.ValidationMessageFor(model => model.HomeAddressState)
这是html输出:
<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>
无论选择哪个选项,StringLength验证都会在客户端失败.我做错了什么?
解决方法
这是相关的jquery验证代码.如您所见,它似乎将长度验证应用于所选选项的数量,而不是选项的长度.似乎只适用于多选列表框.有点奇怪,说实话.
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; }