asp.net data annotations field length

时间秒杀一切 提交于 2019-12-11 06:31:01

问题


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:


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.



来源:https://stackoverflow.com/questions/12604576/asp-net-data-annotations-field-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!