日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

ASP.NET?MVC使用正則表達式驗證手機號碼_實用技巧

作者:Darren?Ji ? 更新時間: 2022-11-04 編程語言

在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="提交"/>
}

原文鏈接:https://www.cnblogs.com/darrenji/p/4247994.html

欄目分類
最近更新