在ASP.NET MVC中对手机号码的验证
在ASP.NET MVC中,可以使用RegularExpression特性来验证手机号码。
public class Customer{[Required(ErrorMessage = "必填")]
[Display(Name = "手机号")]
[RegularExpression(@"^1[3458][0-9]{9}$", ErrorMessage = "手机号格式不正确")]public string PhoneNumber { get; set; }}
在HomeController中:
public class HomeController : Controller{public ActionResult Index()
{return View(new Customer());}[HttpPost]public ActionResult Index(Customer customer)
{if (ModelState.IsValid)
{return Content("ok");}else
{return View(customer);
}}}
在Views/Shared/_Layout.cshtml中,必须引用异步验证的相关js。
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
在Home/Index.cshtml中:
@model MvcApplication1.Models.Customer@{ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}<h2>Index</h2>@using (Html.BeginForm("Index", "Home", FormMethod.Post)){@Html.LabelFor(m => m.PhoneNumber)@Html.TextBoxFor(m => m.PhoneNumber)@Html.ValidationMessageFor(m => m.PhoneNumber)<br/><input type="submit" value="提交"/>}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。