MaxLength Attribute not generating client-side validation attributes

128,670

Solution 1

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

That's for validation purposes. If you want to set for example the maxlength attribute on the input you could write a custom data annotations metadata provider as shown in this post and customize the default templates.

Solution 2

I just used a snippet of jquery 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 of the elements that have a data-val-length-max attribute set. This is the attribute that the StringLength validation attribute will set.

The each loop loops through these matches and will parse out the value for this attribute and assign it to the mxlength property that should have been set.

Just add this to you document ready function and you are good to go.

Solution 3

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

@Html.TextBoxFor(model => model.Item3.ADR_ZIP, new { @class = "gui-input ui-oblig", @maxlength = "5" })

Solution 4

MaxLengthAttribute is working since MVC 5.1 update: change notes

Solution 5

Props to @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 the parseInt() is for there? I've simplified it to this with no problems...

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

I would have commented on Nicks answer but don't have enough rep yet.

Share:
128,670
Matt Jenkins
Author by

Matt Jenkins

Updated on July 08, 2022

Comments

  • Matt Jenkins
    Matt Jenkins almost 2 years

    I have a curious problem 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 view:

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

    And here's the generated HTML I get for the textbox 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="">
    

    No sign of the MaxLengthAttribute, but everything else seems to be working.

    Any ideas what's going wrong?

  • Matt Jenkins
    Matt Jenkins almost 13 years
    Thank you very much. In case anyone is wondering, I checked that EF Code First creates the DB column with the maximum length imposed by the StringLength attribute. :)
  • Hryhorii
    Hryhorii almost 13 years
    But this is not the answer. Because MinLength attribute too not work
  • Caleb Vear
    Caleb Vear almost 13 years
    @Greg, the StringLength attribute can specify a maximum and minimum length.
  • Jeremy Holovacs
    Jeremy Holovacs over 12 years
    What if you don't want to specify a max length, just a min? You have suggested a mostly functional workaround, but it does not address the issue that the validation attribute is not validating properly.
  • Darin Dimitrov
    Darin Dimitrov over 12 years
    @JeremyHolovacs, if you don't want to specify a max you simply specify int.MaxValue as max length and then set the MinLength property to whatever minimum length you need. So, no, it's not just a functional workaround. It's one that works in practice as well.
  • Jeremy Holovacs
    Jeremy Holovacs over 12 years
    @DarinDimitrov if you specify int.MaxValue you are specifying a max length, because you have to. While functionally identical, you are now explicitly specifying something that you wouldn't have to with MinLength and MaxLength. This still does not address the issue that the validation attribute is not validating properly, and most people find this out the hard way.
  • Darin Dimitrov
    Darin Dimitrov over 12 years
    @JeremyHolovacs, personally I don't use data annotations to perform validation. I find them very limiting and counter intuitive. I prefer imperative validation rather than declarative. It gives me more control. I use FluentValidation.NET.
  • Andy
    Andy about 12 years
    The problem with this answer is that MaxLength DOES correctly work server side, so saying MaxLength isn't for validation purposes seems odd.
  • Mike Cole
    Mike Cole almost 11 years
    @Andy - MaxLength is for validation purposes - just not for client-side validation purposes.
  • Andy
    Andy almost 11 years
    @MikeCole I believe the RangeAttribute in the same namespace does correctly cause client side validation to be emitted. Its supposed to be one of the selling points of Asp.Net MVC; it will pick up validation attributes and apply client side logic for the built-in ones.
  • TheOptimusPrimus
    TheOptimusPrimus almost 11 years
    This is pretty slick.
  • ladenedge
    ladenedge over 9 years
    It does now work for validation, but MVC still is not applying the maxlength attribute to the input element.
  • toha
    toha about 8 years
    Nice, Demit.. You are awesome!
  • hatsrumandcode
    hatsrumandcode about 8 years
    you can use .data("val-length-max") instead of .attr("data-val-length-max") :)
  • Christian Gollhardt
    Christian Gollhardt about 7 years
    I wrote an framework extension, that exactly does this @ladenedge
  • Yang Yu
    Yang Yu almost 5 years
    Please add description