StringLength/Minlength validation doesn't prevent user from posting the form with no value

asp.net-mvc, validation, web

Solution

It is by design.

This is the validation logic for StringLength:

public override bool IsValid(object value)
{
  this.EnsureLegalLengths();
  int num = value == null ? 0 : ((string) value).Length;
  if (value == null)
    return true;
  if (num >= this.MinimumLength)
    return num <= this.MaximumLength;
  else
    return false;
}

As you can see, when the string is null `StringLength` returns true.

Problem

I have the following property on my ViewModel ``` [StringLength(20, MinimumLength = 1, ErrorMessageResourceName = "Error_StringLength", ErrorMessageResourceType = typeof(Global))] public string LeagueName { get; set; } ``` If the string ends up being larger than 20 characters the validation will fire and not allow the user to post the form. However, if the field is blank, which means that the LeagueName property has a length of less than 1 it will allow the user to post the form. I know this is easily resolved by using the Required attribute, but why is the validation not working as expected in this scenario?

Original source