我想在我的cshtml文件中设置正则表达式,请帮我怎么做?我不想先在代码中使用正则表达式。
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control", placeholder = "short name", required = "required", RegularExpressionAttribute = @"^([a-zA-Z .&'-]+)$" } })
@Html.ValidationMessageFor(model => model.Title,"", new { @class = "text-danger" })
</div>
</div>
答案 0 :(得分:4)
这很有效。您需要将EditorFor更改为TextBoxFor。删除htmlAttributes,并使用pattern而不是RegularExpressionAttribute:
型号:
namespace Testy20161006.Models
{
public class Student
{
public int ID { get; set; }
public String Name { get; set; }
public String email { get; set; }
}
}
控制器:
[HttpPost]
public ActionResult Index9(Student stud)
{
if (ModelState.IsValid)
{
var ap = "dh";
}
return View(stud);
}
public ActionResult Index9()
{
return View(new Student());
}
查看:
@model Testy20161006.Models.Student
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index9</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<link href="~/Content/Student.css" rel="stylesheet" />
</head>
<body>
<div>
@using (Html.BeginForm())
{
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.TextBoxFor(model => model.Name, new { @class = "form-control", placeholder = "short name", required = "required", pattern = @"^([a-zA-Z .&'-]+)$" })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
<input type="submit" value="Submit" />
}
</div>
</body>
</html>