I currently have the following data annotation on a field
[StringLength(1000, MinimumLength = 6, ErrorMessage = "field must be atleast 6 characters")]
public string myField {get;set;}
Can I change the data annotation such that it works only if the user types something in the field? In other words, it is okay to leave the field empty but if the user types a value in the field, it should be between 6-1000 characters in length.
That’s already the case with the
StringLengthattribute. If you leave the field empty the model will be valid. Didn’t you even try this out?Model:
Controller:
View:
You could leave the field empty and you won’t get a validation error.