Search code examples
c#asp.netasp.net-mvc-3validationattributes

How does the StringLengthAttribute work?


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.


Solution

  • 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.