数据注释上的正则表达式



我在MVC3模型上有一个正则表达式,它需要检查字符串的第一个字符,以确保它以零开始,后面跟着另外6个数字,这就是我所拥有的:

[RegularExpression(@"^0", ErrorMessage = "value must start with a zero.")]

无论我在字段中输入什么,它都会返回错误消息:

1 = error
0 = error
0000000 = error message

有什么想法吗

谢谢

尝试如下:

[RegularExpression(@"^0[d]{6}$", ErrorMessage = "Value must start with a zero.")]

奇怪,下面的对我来说很好:

模型:

public class MyViewModel
{
    [RegularExpression(@"^0[0-9]{6}$", ErrorMessage = "value must start with a zero.")]
    public string Value { get; set; }
}

控制器:

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

视图:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Value)
    @Html.ValidationMessageFor(x => x.Value)
    <button type="submit">OK</button>
}

最新更新