How does the StringLengthAttribute work?

32,951

Solution 1

Yes, that is the correct behavior. StringLength verifies that a string is a certain length, but does not REQUIRE that the string be entered. Decorate Description with [Required], so that you have both a requirement for the string, and StringLength will provide the constraints on the string length.

Solution 2

Keyword as follows:

 class PartMetadata
 {
     // required keyword forces user to enter input
     [Required] 
     [DisplayName("Part number")]
     // or [Required(ErrorMessage="* Required")]

     // ErrorMessage in string only enforces when data is entered
     [StringLength(50, MinimumLength = 3, ErrorMessage = "* Part numbers must be between 3 and 50 character in length.")]
     public string Number { get; set; }
Share:
32,951

Related videos on Youtube

Benjamin Gale
Author by

Benjamin Gale

I am interested in the following: C# Winforms WPF XNA Python Database design / development Cocoa Objective-C Haskell

Updated on July 09, 2022

Comments

  • Benjamin Gale
    Benjamin Gale almost 2 years

    I am having trouble using the StringLengthAttribute when validating my model using Entity Framework and ASP.NET MVC3.

    My model is based on an Entity Framework entity which has a partial class that uses the MetadataType attribute to tell the MVC which type to use when searching for metadata. This is shown in the code below:

    [MetadataType(typeof(PartMetadata))]
    public partial class Part { }
    
    class PartMetadata
    {
        [DisplayName("Part number")]
        [Required(ErrorMessage="* Required")]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "* Part numbers must be between 3 and 50 character in length.")]
        public string Number { get; set; }
    
        [StringLength(255, MinimumLength=3,
            ErrorMessage="* Part descriptions must be between 3 and 255 characters in length.")]
        public string Description { get; set; }
    
        [DisplayName("Drawing required?")]
        public bool DrawingRequired { get; set; }
    }
    

    The problem I am having is that the description field is not being validated properly. Using the code below my model is validated as OK and I am redirected to the Index page of my controller even when the description field is left blank.

    if (ModelState.IsValid)
    {
        return RedirectToAction("Index");
     }
     else
     {
         return View();
      }
    

    If I add a RequiredAttribute to the description field then my model is classed as being in an invalid state and my form is reloaded showing the default error message of the required attribute. If I subsequently edit the description field then it shows the validation error message I have set in the string length attribute.

    Is this how the attribute should behave? It isn't a problem decorating the properties with the required attribute but seems counterintuitive as the field isn't required I just want to ensure that if the user does type something then it falls within the range of the string length attribute.

    • Joao
      Joao over 12 years
      As I understand, this is exactly working as you expect it to. It is just validating the string length if the user does type something. If you really want him/her to type something, [Required] is needed, just as you said. What's the behavior you are searching for?
    • Joao
      Joao over 12 years
      Lefting the field blank is considered null and that's when [Required] attribute triggers.
  • Benjamin Gale
    Benjamin Gale over 12 years
    Thanks. This actually makes perfect sense and it was the null string that was throwing me. I have verified that this works. Thank you.
  • Spyros_Spy
    Spyros_Spy over 5 years
    Why doesn't [Required(ErrorMessage="* Required")] ensure that the field is Required and we need to also put a [Required] tag before it?
  • Joseph Poirier
    Joseph Poirier over 5 years
    I believe the top one just turns the DisplayName red if the data is missing & the latter one displays the error message. in theory you could print any error message U choose. The stringLength requirement, also fails to show up when the item is missing, even though there's a low length > 0. Initially, I thought that would do the trick, then went on trying various items. Also consider, these property items can & will differ sometimes between versions.
  • Spyros_Spy
    Spyros_Spy over 5 years
    I just did an example and it marked the second [Required] field that had the error message inside, as duplicate.
  • Joseph Poirier
    Joseph Poirier over 5 years
    Your version or update of your VS edition has the bug fix correcting the issue. I sometimes use beta's & report things that I feel are lacking common sense. I think VS 2012 did not throw the error, but at least one beta required both for some reason, which I thought was inefficient. I don't believe anything beyond 2013 requires both, only one or the other.
  • Joseph Poirier
    Joseph Poirier over 5 years
    Also consider the original question was MVC 3.0, we are now on MVC 4.0 or above in most cases