ASP.NET MVC 使用Remote特性實現遠程屬性驗證

RemoteAttribute是asp.net mvc 的一個驗證特性,它位於System.Web.Mvc命名空間html

下面經過例子來講明jquery

不少系統中都有會員這個功能,會員在前臺註冊時,用戶名不能與現有的用戶名重複,還要求輸入手機號碼去註冊,同時手機號碼也須要驗證是否重複,下面是實體類數據庫

複製代碼
/// <summary>
/// 會員
/// </summary>
public class Member
{
    public int Id { get; set; }

    [Required(ErrorMessage = "請填寫用戶名")]
    [Remote("CheckName","Member",HttpMethod = "POST")]
    public string Name { get; set; }

    [Required(ErrorMessage = "請填寫密碼")]
    [StringLength(16, ErrorMessage = "請填寫6到16位的密碼",MinimumLength = 6)]
    public string Password { get; set; }

    [Required(ErrorMessage = "請填寫手機號碼")]
    [RegularExpression(@"^1\d{10}$",ErrorMessage = "手機號碼格式錯誤")]
    [Remote("CheckMobile", "Member", HttpMethod = "POST")]
    public string Mobile { get; set; }

}
複製代碼

Controller類mvc

複製代碼
public class MemberController : Controller
    {
        // GET: Member
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(Member model)
        {
            if (ModelState.IsValid)
            {

            }
            return View(model);
        }
        [HttpPost]
        public JsonResult CheckName(string Name)
        {
            //這裏假設已經有了test這個會員,若是註冊時填寫的也是test這個會員,則已存在會員,驗證不經過
            //這裏只是模擬,實際的狀況是讀取數據庫等去判斷是否存在該用戶名的會員
            if (!string.IsNullOrWhiteSpace(Name) &&  Name.Trim() == "test")
            {
                return Json("用戶名" + Name + "已存在", JsonRequestBehavior.AllowGet);
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult CheckMobile(string Mobile)
        {
            //這裏假設已經有了手機號碼10000000000已經註冊,若是使用該號碼註冊,則驗證不經過
            //注意:這裏的號碼10000000000不具備真實性,只是舉例使用
            //這裏只是模擬,實際的狀況是讀取數據庫等去判斷是否存在該手機號碼的會員
            if (!string.IsNullOrWhiteSpace(Mobile) && Mobile.Trim() == "10000000000")
            {
                return Json("手機號碼已被註冊", JsonRequestBehavior.AllowGet);
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }
    }
複製代碼

視圖asp.net

複製代碼
@model RemoteDemoWeb.Models.Member

@{
    ViewBag.Title = "Create";
    Html.EnableClientValidation();
    Html.EnableUnobtrusiveJavaScript();
}

<h2>Create</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Member</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Mobile, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section scripts{
    
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    }
複製代碼

這裏調用了Html.EnableClientValidation(); 和Html.EnableUnobtrusiveJavaScript();   同時引入jquery.validate.js 和jquery.validate.unobtrusive.jside

前臺瀏覽,並填寫信息ui

 

當填寫存在的用戶名和手機號碼時spa

上面例子是基於ASP.NET MVC 5.net

相關文章
相關標籤/搜索