4

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.

1 Answer 1

20

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.

2
  • See my update. Maybe you have a [Required] attribute on your property as well? For example this attribute could be hidden in some partial class generated by the EF framework for you that you haven't noticed. Sep 26, 2012 at 15:13
  • Thanks! Silly me. I had the [Required] property which was causing the error
    – user1625066
    Sep 26, 2012 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.