MaxLength attribute does not generate client-side validation attributes

I have a curious issue with ASP.NET MVC3 client side validation. I have the following class:

public class Instrument : BaseObject { public int Id { get; set; } [Required(ErrorMessage = "Name is required.")] [MaxLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")] public string Name { get; set; } } 

From my point of view:

 <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> 

And here is the generated HTML I get for the text field for this field:

 <input class="text-box single-line" data-val="true" data-val-required="Name is required." id="Name" name="Name" type="text" value=""> 

There is no MaxLengthAttribute sign, but everything else works.

Any ideas what is going wrong?

+75
c # validation asp.net-mvc asp.net-mvc-3 model-validation
Jul 23 '11 at 16:10
source share
11 answers

Try using the [StringLength] attribute:

 [Required(ErrorMessage = "Name is required.")] [StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")] public string Name { get; set; } 

This is for verification purposes. If you want to set, for example, the maxlength attribute on the input, you can write the metadata creator of the user annotation data as shown in this post , and configure the default templates .

+139
Jul 23 '11 at 19:23
source share

I just used a jquery snippet to solve this problem.

 $("input[data-val-length-max]").each(function (index, element) { var length = parseInt($(this).attr("data-val-length-max")); $(this).prop("maxlength", length); }); 

The selector finds all elements that have the data-val-length-max attribute set. This is the attribute that the StringLength validation attribute will be set to.

Each cycle goes through these matches and will parse the value for this attribute and assign it the mxlength property that should have been set.

Just add this feature to the document and you will go well.

+36
Jan 04 '13 at 22:34
source share

MaxLengthAttribute works with MVC 5.1 update: change notes

+8
Feb 11 '14 at 8:24
source share

In MVC 4, If you want maxlenght to type in input type text? You can!

 @Html.TextBoxFor(model => model.Item3.ADR_ZIP, new { @class = "gui-input ui-oblig", @maxlength = "5" }) 
+6
May 20 '16 at 23:18
source share

Reputation @ Nick-Harrison for his answer:

 $("input[data-val-length-max]").each(function (index, element) { var length = parseInt($(this).attr("data-val-length-max")); $(this).prop("maxlength", length); }); 

I was wondering what parseInt () is? I simplified this without any problems ...

 $("input[data-val-length-max]").each(function (index, element) { element.setAttribute("maxlength", element.getAttribute("data-val-length-max")) }); 

I would comment on Nicks answer, but have not received enough rep yet.

+4
Jul 27 '16 at 10:35
source share

I had the same problem and was able to solve it by implementing the IValidatableObject interface in my view model.

 public class RegisterViewModel : IValidatableObject { /// <summary> /// Error message for Minimum password /// </summary> public static string PasswordLengthErrorMessage => $"The password must be at least {PasswordMinimumLength} characters"; /// <summary> /// Minimum acceptable password length /// </summary> public const int PasswordMinimumLength = 8; /// <summary> /// Gets or sets the password provided by the user. /// </summary> [Required] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } /// <summary> /// Only need to validate the minimum length /// </summary> /// <param name="validationContext">ValidationContext, ignored</param> /// <returns>List of validation errors</returns> public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { var errorList = new List<ValidationResult>(); if ((Password?.Length ?? 0 ) < PasswordMinimumLength) { errorList.Add(new ValidationResult(PasswordLengthErrorMessage, new List<string>() {"Password"})); } return errorList; } } 

Then the markup in Razor ...

 <div class="form-group"> @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password, new { @class = "form-control input-lg" } <div class="password-helper">Must contain: 8 characters, 1 upper-case, 1 lower-case </div> @Html.ValidationMessagesFor(m => m.Password, new { @class = "text-danger" }) </div> 

It works very well. If I try to use [StringLength] instead, the displayed HTML is simply incorrect. Validation should appear as:

 <span class="text-danger field-validation-invalid field-validation-error" data-valmsg-for="Password" data-valmsg-replace="true"><span id="Password-error" class="">The Password should be a minimum of 8 characters long.</span></span> 

Using StringLengthAttribute, the rendered HTML is displayed as a ValidationSummary, which is incorrect. The funny thing is that when the validator fails, the feed is still blocked!

+3
Apr 21 '16 at 22:24
source share

StringLength works fine, I used it like this:

 [StringLength(25,MinimumLength=1,ErrorMessage="Sorry only 25 characters allowed for ProductName")] public string ProductName { get; set; } 

or Just use RegularExpression without StringLength:

 [RegularExpression(@"^[a-zA-Z0-9'@&#.\s]{1,25}$", ErrorMessage = "Reg Says Sorry only 25 characters allowed for ProductName")] public string ProductName { get; set; } 

but for me the above methods gave an error in the display view because I already had a ProductName field in the database that had more than 25 characters

so finally I came across this and this and tried to check without a model :

  <div class="editor-field"> @Html.TextBoxFor(model => model.ProductName, new { @class = "form-control", data_val = "true", data_val_length = "Sorry only 25 characters allowed for ProductName", data_val_length_max = "25", data_val_length_min = "1" }) <span class="validation"> @Html.ValidationMessageFor(model => model.ProductName)</span> </div> 

this solved my problem, you can also do the check manually using jquery or using ModelState.AddModelError

Hope helps someone.

+2
May 03 '15 at 11:58 a.m.
source share

I know that I'm very late to the party, but I finally found out how we can register MaxLengthAttribute .

First we need a validator:

 public class MaxLengthClientValidator : DataAnnotationsModelValidator<MaxLengthAttribute> { private readonly string _errorMessage; private readonly int _length; public MaxLengthClientValidator(ModelMetadata metadata, ControllerContext context, MaxLengthAttribute attribute) : base(metadata, context, attribute) { _errorMessage = attribute.FormatErrorMessage(metadata.DisplayName); _length = attribute.Length; } public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { var rule = new ModelClientValidationRule { ErrorMessage = _errorMessage, ValidationType = "length" }; rule.ValidationParameters["max"] = _length; yield return rule; } } 

Nothing special. In the constructor, we store some values ​​from the attribute. In GetClientValidationRules we set the rule. ValidationType = "length" maps to a data-val-length wireframe. rule.ValidationParameters["max"] for the data-val-length-max attribute.

Now that you have a validator, you only need to register it in global.asax :

 protected void Application_Start() { //... //Register Validator DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MaxLengthAttribute), typeof(MaxLengthClientValidator)); } 

Et voila, it just works.

+1
Apr 21 '17 at 17:45
source share

I tried this for all inputs in my html document (textarea, input, etc.) that had the data-val-length-max property and it works correctly.

 $(document).ready(function () { $(":input[data-val-length-max]").each(function (index, element) { var length = parseInt($(this).attr("data-val-length-max")); $(this).prop("maxlength", length); }); }); 
+1
Oct. 16 '17 at 18:13
source share

It can replace MaxLength and MinLength

 [StringLength(40, MinimumLength = 10 , ErrorMessage = "Name cannot be longer than 40 characters and less than 10")] 
0
Nov 19 '16 at 3:31
source share
 <input class="text-box single-line" data-val="true" data-val-required="Name is required." id="Name1" name="Name" type="text" value=""> $('#Name1').keypress(function () { if (this.value.length >= 5) return false; }); 
0
Jun 27. '19 at 18:08
source share



All Articles