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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM