溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

ASP.NET?MVC中如何使用正則表達式驗證手機號碼

發(fā)布時間:2022-10-20 14:58:39 來源:億速云 閱讀:113 作者:iii 欄目:開發(fā)技術(shù)

這篇“ASP.NET MVC中如何使用正則表達式驗證手機號碼”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“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中,必須引用異步驗證的相關(guān)js。

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")

在Home/Index.cshtml中:

@model MvcApplication1.Models.Customer
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>Index</h3>
@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="提交"/>
}

以上就是關(guān)于“ASP.NET MVC中如何使用正則表達式驗證手機號碼”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI