0

I need to control a field with a min length if someone enters a value but if they don't enter anything in, I don't want the form to tell them there is a min value.

This is what I have:

[Required]
[StringLength(15, ErrorMessage = "Please supply at least {2} characters.", MinimumLength = 3)]
[Display(Name = "Last name on account or first part of the company's name")]
public string LastName { get; set; }

I just need for it to allow blanks also or if data is entered, require it to be a min of 3 characters..

Any suggestions?

ErocM
  • 4,505
  • 24
  • 94
  • 161
  • **[Can you please check here. Hope you will find it useful.](http://stackoverflow.com/questions/18276853/string-minlength-and-maxlength-validation-dont-work-asp-net-mvc/18276949#18276949)** – Imad Alazani Aug 24 '13 at 19:24
  • Similar: http://stackoverflow.com/questions/5487094/asp-net-mvc3-model-validation-string-is-null-or-if-not-has-min-length-of-x – SepehrM Feb 21 '17 at 12:03

1 Answers1

2

The problem is with the validation logic of the StringLength attribute, that returns true also for the string with null value, here the implementation:

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

Also the Required attribute that you used is not helping :-).

Anyway the only thing you can do for your scenario is to create a custom attribute to validate LastName with the logic that you need, here a link to an MVC3 example, or you can try googling, there is a lot of examples and is not hard to implement.

Daniele
  • 1,938
  • 16
  • 24
  • All I needed to do was remove the required. Overlooked it a 100 times... Thanks for the help! – ErocM Aug 24 '13 at 21:15