Search code examples
c#data-annotationsasp.net-web-api2

Allow a property to be null or a specified length


I have the following definition.

[StringLength(4, MinimumLength = 4, ErrorMessage = "Mobile Last 4 must be 4 digits.")]
public string MobileLast4 { get; set; }

I want to be able to use null or if the field does have a value then it needs to be 4 characters in length.

The problem I'm running into is if the property is null the validation fails. Is there another attribute I should use or do I need to roll my own?

I suppose I could use a nullable int with a range attribute which would solve this problem, but I have other properties that don't accept numbers.


Solution

  • Using the [StringLength] attribute does not make the field required. If your validation fails it is not caused by the code that you have shown.