Reputation:
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.
Upvotes: 4
Views: 27132
Reputation: 1038710
That's already the case with the StringLength
attribute. If you leave the field empty the model will be valid. Didn't you even try this out?
Model:
public class MyViewModel
{
[StringLength(1000, MinimumLength = 6, ErrorMessage = "field must be atleast 6 characters")]
public string MyField { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.MyField)
@Html.ValidationMessageFor(x => x.MyField)
<button type="submit">OK</button>
}
You could leave the field empty and you won't get a validation error.
Upvotes: 20