asp.net数据注释字段长度

1 data-annotations asp.net-mvc-3

我目前在一个字段上有以下数据注释

[StringLength(1000, MinimumLength = 6, ErrorMessage = "field must be atleast 6 characters")]
public string myField {get;set;}
Run Code Online (Sandbox Code Playgroud)

我是否可以更改数据注释,使其仅在用户在字段中键入内容时才有效?换句话说,可以将该字段留空,但如果用户在字段中键入值,则其长度应介于6-1000个字符之间.

Dar*_*rov 15

StringLength属性就是这种情况.如果将该字段留空,则模型将有效.你有没有试过这个?

模型:

public class MyViewModel
{
    [StringLength(1000, MinimumLength = 6, ErrorMessage = "field must be atleast 6 characters")]
    public string MyField { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}
Run Code Online (Sandbox Code Playgroud)

视图:

@model MyViewModel

@using (Html.BeginForm())
{ 
    @Html.EditorFor(x => x.MyField)
    @Html.ValidationMessageFor(x => x.MyField)
    <button type="submit">OK</button>
}
Run Code Online (Sandbox Code Playgroud)

您可以将该字段留空,您将不会收到验证错误.