Asp.Mvc 2.0用戶服務(wù)器驗(yàn)證實(shí)例講解(4)
這一節(jié)給大家講解下ASP.NET MVC 2.0的服務(wù)器端驗(yàn)證的用法。大家知道,一個(gè)項(xiàng)目只用JS客戶端驗(yàn)證是不安全的,用戶可以禁用JS來(lái)繞過(guò)客戶端驗(yàn)證,所以必須有服務(wù)器端驗(yàn)證。
關(guān)于服務(wù)器端驗(yàn)證,主要調(diào)用System.ComponentModel.DataAnnotations命名空間里面的類庫(kù)。
咱們這次還是以注冊(cè)頁(yè)面為例來(lái)講解服務(wù)器端驗(yàn)證,主要對(duì)注冊(cè)頁(yè)面完成以下驗(yàn)證
1.用戶名不能為空
2.密碼不能為空,密碼長(zhǎng)度不能小于5位數(shù),
3.密碼和確認(rèn)密碼輸入必須一樣
4.郵件格式必須正確
咱們先看下效果圖
MVC中對(duì)所有字段的驗(yàn)證,實(shí)際上只需要在MODEL層設(shè)置驗(yàn)證規(guī)則就可以。
1.用戶名驗(yàn)證
對(duì)用戶名的驗(yàn)證,只需要驗(yàn)證用戶名不為空就可以了,使用Required屬性,把此屬性綁定到MODEL的用戶名字段上就可以了。
/// <summary> /// 用戶名 /// </summary> [DisplayName("用戶名")] [Required(ErrorMessage="用戶名不能為空!")] public string UserName { get; set; }
Required里面的參數(shù)表示具體的提示信息,此時(shí)如果用戶名為空,就會(huì)在前臺(tái)ASPX頁(yè)面出現(xiàn)用戶名不能為空的提示。當(dāng)然要在前臺(tái)顯示錯(cuò)誤的提示信息。使用<%:Html.ValidationMessageFor(m=>m.UserName)%>標(biāo)記就可以在前臺(tái)顯示錯(cuò)誤的提示信息
2.密碼驗(yàn)證
密碼驗(yàn)證包括密碼不能為空和密碼長(zhǎng)度限制。
驗(yàn)證密碼為空和驗(yàn)證用戶名為空一樣,使用Required屬性。
驗(yàn)證密碼的長(zhǎng)度使用StringLength屬性。
/// <summary> /// 密碼 /// </summary> [DisplayName("密碼")] [Required(ErrorMessage="密碼不能為空")] [StringLength(10, ErrorMessage = "密碼長(zhǎng)度不能小于5位",MinimumLength=5)] public string UserPwd { get; set; }
StringLength的第一個(gè)參數(shù)表示密碼的最大長(zhǎng)度,ErrorMessage表示不滿足條件的時(shí)候的錯(cuò)誤提示信息。
MinimumLength表示輸入內(nèi)容的最小長(zhǎng)度.
當(dāng)然,前臺(tái)必須有地方顯示錯(cuò)誤信息,顯示錯(cuò)誤信息我們使用如下
<%:Html.ValidationMessageFor(m=>m.UserPwd)%>
3.驗(yàn)證密碼和確認(rèn)密碼是否一致
要驗(yàn)證密碼和確認(rèn)密碼是否一致,這個(gè)稍微有點(diǎn)復(fù)雜,需要我們自定義驗(yàn)證規(guī)則。自定義驗(yàn)證規(guī)則我們需要繼承ValidationAttribute類.然后實(shí)現(xiàn)它的isvaild方法。
/// <summary> /// 此自定義類用于驗(yàn)證密碼和確認(rèn)密碼必須一致 /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public class PwdMatch :ValidationAttribute { private object _typeid = new object(); public string PWD { get; set; }//密碼 public string ConfirmPwd { get; set; }//確認(rèn)密碼 public PwdMatch(string pwd, string confirmPwd) : base() { PWD = pwd; ConfirmPwd = confirmPwd; } /// <summary> /// 返回錯(cuò)誤的提示信息 /// </summary> /// <param name="name"></param> /// <returns></returns> public override string FormatErrorMessage(string name) { return ErrorMessage; } /// <summary> /// 重寫TYPEID /// </summary> public override object TypeId { get { return _typeid; } } /// <summary> /// 判斷是否想到 /// </summary> /// <param name="value">value的值實(shí)際上是MODEL提交的MODEL類</param> /// <returns></returns> public override bool IsValid(object value) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); object originalValue = properties.Find(PWD, true ).GetValue(value);//獲取密碼 object confirmValue = properties.Find(ConfirmPwd, true).GetValue(value);//獲取確認(rèn)密碼的值 return Object.Equals(originalValue, confirmValue); } } PwdMatch屬性類創(chuàng)建后,可把它標(biāo)記在注冊(cè)MODEL的上面,然后提交注冊(cè)的時(shí)候,就會(huì)驗(yàn)證了 [PwdMatch("UserPwd","ConfirPwd", ErrorMessage ="密¨¹碼?與®?確¨¡¤認(rèn)¨?不?匹£¤配?")] public class RegisterModel { }
PwdMatch的第一個(gè)參數(shù)表上密碼,名稱與RegisterModel中的密碼屬性相同,第二個(gè)字段是確認(rèn)密碼,名稱與RegisterModel與的確認(rèn)密碼屬性相同,最后一個(gè)參數(shù)是錯(cuò)誤提示信息。
當(dāng)然,也要在前臺(tái)顯示錯(cuò)誤提示信息,使用<%:Html.ValidationSummary(true,"用®?戶¡ì創(chuàng)ä¡ä建¡§失º¡ì敗㨹!")%>就可以在前臺(tái)顯示一個(gè)總的錯(cuò)誤信息列表。
4.郵箱驗(yàn)證
郵箱驗(yàn)證主要是郵箱格式驗(yàn)證,驗(yàn)證格式是否滿足要求.驗(yàn)證郵箱我們使用RegularExpressions屬性就可以。
/// <summary> /// 用戶郵箱 /// </summary> [DisplayName("郵箱")] //[DataType(DataType.EmailAddress)] [RegularExpression(@"^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$", ErrorMessage = "電子郵件格式錯(cuò)誤")] public string Email { get; set; }
第一個(gè)參數(shù)郵箱驗(yàn)證的正則表達(dá)式,第二個(gè)參數(shù)是錯(cuò)誤提示信息。
在ASPX頁(yè)面顯示錯(cuò)誤信息用<%:Html.ValidationMessageFor(m=>m.Email)%>
以上是對(duì)用戶注冊(cè)信息的驗(yàn)證,當(dāng)然,我們?cè)谔峤恍畔⒌臅r(shí)候,要判斷驗(yàn)證是否通過(guò),我們使用ModelState.IsValid來(lái)判斷驗(yàn)證是否通過(guò),TRUE表示通過(guò),F(xiàn)ALSE表示未通過(guò)。
model代碼:
/// <summary> /// 注冊(cè)用戶MODEL /// </summary> [PwdMatch("UserPwd", "ConfirPwd", ErrorMessage = "密碼與確認(rèn)不匹配")] public class RegisterModel { /// <summary> /// 用戶名 /// </summary> [DisplayName("用戶名")] [Required(ErrorMessage="用戶名不能為空!")] public string UserName { get; set; } /// <summary> /// 密碼 /// </summary> [DisplayName("密碼")] [Required(ErrorMessage="密碼不能為空")] [StringLength(10, ErrorMessage = "密碼長(zhǎng)度不能小于5位",MinimumLength=5)] public string UserPwd { get; set; } [DisplayName("確認(rèn)密碼")] [Required(ErrorMessage="確認(rèn)密碼不能為空!")] [StringLength(10, ErrorMessage = "確認(rèn)密碼長(zhǎng)度不能小于5位",MinimumLength=5)] public string ConfirPwd { get; set; } /// <summary> /// 用戶郵箱 /// </summary> [DisplayName("郵箱")] //[DataType(DataType.EmailAddress)] [RegularExpression(@"^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$", ErrorMessage = "電子郵件格式錯(cuò)誤")] public string Email { get; set; } } /// <summary> /// 此自定義類用于驗(yàn)證密碼和確認(rèn)密碼必須一致 /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public class PwdMatch :ValidationAttribute { private object _typeid = new object(); public string PWD { get; set; }//密碼 public string ConfirmPwd { get; set; }//確認(rèn)密碼 public PwdMatch(string pwd, string confirmPwd) : base() { PWD = pwd; ConfirmPwd = confirmPwd; } /// <summary> /// 返回錯(cuò)誤的提示信息 /// </summary> /// <param name="name"></param> /// <returns></returns> public override string FormatErrorMessage(string name) { return ErrorMessage; } /// <summary> /// 重寫TYPEID /// </summary> public override object TypeId { get { return _typeid; } } /// <summary> /// 判斷是否想到 /// </summary> /// <param name="value">value的值實(shí)際上是MODEL提交的MODEL類</param> /// <returns></returns> public override bool IsValid(object value) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); object originalValue = properties.Find(PWD, true ).GetValue(value);//獲取密碼 object confirmValue = properties.Find(ConfirmPwd, true).GetValue(value);//獲取確認(rèn)密碼的值 return Object.Equals(originalValue, confirmValue); } }
前臺(tái)頁(yè)面代碼
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcLogin.Models.RegisterModel>" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>注冊(cè)頁(yè)面</title> <script type="text/javascript" src="../../Scripts/jquery-1.4.1-vsdoc.js"></script> <script type="text/javascript" src="../../Scripts/jquery.validate.js"></script> <script type="text/javascript"> // $().ready(function () { // $("#form1").validate( // { // rules: // { // UserName: // { // required: true // }, // UserPwd: // { // required: true, // minlength: 6 // }, // ConfirPwd: // { // required: true, // minlength: 6, // equalTo: "#UserPwd" // }, // Email: // { // email: true // } // }, // messages: // { // UserName: // { // required: "<span style='color:red'>用戶名不能為空! </span>" // }, // UserPwd: // { // required: "<span style='color:red'>密碼不能為空!</span>", // minlength: jQuery.format("<span style='color:red'>密碼長(zhǎng)度不能小于{0}個(gè)字符!</span>") // }, // ConfirPwd: // { // required: "<span style='color:red'>確認(rèn)密碼不能為空!<span>", // minlength: jQuery.format("確認(rèn)密碼長(zhǎng)度不能小于{0}個(gè)字符!"), // equalTo: "<span style='color:red'>兩次輸入密碼不一致!</span>" // }, // Email: // { // email: "<span style='color:red'>郵箱輸入格式不正確!</span>" // } // }, // onkeyup: false // }); // }); </script> </head> <body> <div> <br /> <p style="font-size:12px;color:red"> <%if (ViewData["msg"] != null) {%> <%:ViewData["msg"]%> <%} %> </p> <br /> <p> <%:Html.ValidationSummary(true,"用戶創(chuàng)建失敗!") %> </p> <%Html.BeginForm("Register", "user", FormMethod.Post, new { name="form1",id="form1"}) ; %> <table> <tr> <td><%: Html.LabelFor(m => m.UserName) %></td> <td> <%: Html.TextBoxFor(m => m.UserName) %></td> <td><%:Html.ValidationMessageFor(m=>m.UserName) %></td> </tr> <tr> <td> <%: Html.LabelFor(m => m.UserPwd) %></td> <td> <%: Html.PasswordFor(m => m.UserPwd) %></td> <td><%:Html.ValidationMessageFor(m=>m.UserPwd) %></td> </tr> <tr> <td> <%: Html.LabelFor(m => m.ConfirPwd) %></td> <td> <%: Html.PasswordFor(m => m.ConfirPwd)%></td> <td><%:Html.ValidationMessageFor(m=>m.ConfirPwd) %></td> </tr> <tr> <td> <%: Html.LabelFor(m => m.Email) %></td> <td> <%: Html.TextBoxFor(m => m.Email) %></td> <td><%:Html.ValidationMessageFor(m=>m.Email) %></td> </tr> <tr> <td> <input type="submit" value="提交" /></td> <td></td> <td></td> </tr> </table> <%Html.EndForm(); %> </div> </body> </html>
controller代碼
/// <summary> /// 注冊(cè)提交 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public ActionResult Register(Models.RegisterModel model) { if (ModelState.IsValid) { //驗(yàn)證通過(guò) bool result = false; if (!new Models.SqlHelper().ExistUser(model)) { result = new Models.SqlHelper().AddUser(model); } if (result) { //添加成功轉(zhuǎn)向主頁(yè) FormsService.SignIn(model.UserName, false); return RedirectToAction("index"); } else { //返回注冊(cè)頁(yè)面 ViewData["msg"] = "添加用戶失敗"; return View(model); } } else { //驗(yàn)證不通過(guò) //返回注冊(cè)頁(yè)面 ViewData["msg"] = "添加用戶失敗"; return View(model); } }
以上就是Asp.Mvc 2.0用戶服務(wù)器驗(yàn)證實(shí)例的實(shí)現(xiàn)全過(guò)程,希望大家可以結(jié)合上一篇客戶端驗(yàn)證進(jìn)行練習(xí),希望這篇文章可以更好地幫助大家掌握Asp.Mvc 2.0驗(yàn)證功能。
- asp.net之生成驗(yàn)證碼的方法集錦(一)
- 詳解ASP.NET七大身份驗(yàn)證方式以及解決方案
- ASP.NET中驗(yàn)證控件的使用方法
- ASP.NET MVC3網(wǎng)站創(chuàng)建與發(fā)布(1)
- ASP.NET MVC3模板頁(yè)的使用(2)
- ASP.NET MVC4之js css文件合并功能(3)
- Asp.Mvc?2.0實(shí)現(xiàn)用戶注冊(cè)實(shí)例講解(1)
- Asp.Mvc 2.0實(shí)現(xiàn)用戶登錄與注銷功能實(shí)例講解(2)
- Asp.Mvc?2.0用戶客戶端驗(yàn)證實(shí)例講解(3)
- 創(chuàng)建第一個(gè)ASP.NET應(yīng)用程序(第1節(jié))
- ASP.NET網(wǎng)站模板的實(shí)現(xiàn)(第2節(jié))
- ASP.NET網(wǎng)站聊天室的設(shè)計(jì)與實(shí)現(xiàn)(第3節(jié))
- ASP.NET實(shí)現(xiàn)用戶注冊(cè)和驗(yàn)證功能(第4節(jié))
- ASP.NET在線文本編輯控件的使用(第6節(jié))
- ASP.NET實(shí)現(xiàn)數(shù)據(jù)的添加(第10節(jié))
- ASP.NET用戶注冊(cè)實(shí)戰(zhàn)(第11節(jié))
- Asp.Mvc 2.0用戶的編輯與刪除實(shí)例講解(5)
- ASP.NET對(duì)大文件上傳的解決方案
- Asp.Net上傳圖片同時(shí)生成高清晰縮略圖
- ASP.NET MVC5添加驗(yàn)證(4)
相關(guān)文章
ASP.NET 2.0下隨機(jī)讀取Access記錄的實(shí)現(xiàn)方法
ASP.NET 2.0下隨機(jī)讀取Access記錄的實(shí)現(xiàn)方法...2007-03-03ASP.NET MVC 4使用PagedList.Mvc分頁(yè)的實(shí)現(xiàn)代碼
本篇文章主要介紹了ASP.NET MVC 4使用PagedList.Mvc分頁(yè)的實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07ASP.NETWeb服務(wù)器驗(yàn)證控件如何使用
這篇文章主要介紹了ASP.NETWeb服務(wù)器驗(yàn)證控件如何使用,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2015-09-09ASP.NET MVC中異常Exception攔截的深入理解
異常信息的處理在程序中非常重要, 在asp.net mvc中提供異常屬性攔截器進(jìn)行對(duì)異常信息的處理,下面這篇文章主要給大家介紹了關(guān)于ASP.NET MVC中異常Exception攔截的相關(guān)資料,需要的朋友可以參考下2018-07-07aspxgridview CustomButtonCallback 不支持彈出消息提示解決方法
aspxgridveiw是devexpress的一個(gè)grid控件,使用起來(lái)還不錯(cuò),不能再 CustomButtonCallback 事件中使用response.write,具體的解決方法如下,感興趣的朋友可以參考下哈2013-06-06EntityFramework 6.x學(xué)習(xí)之多個(gè)上下文遷移實(shí)現(xiàn)分布式事務(wù)詳解
這篇文章主要給大家介紹了關(guān)于EntityFramework 6.x學(xué)習(xí)之多個(gè)上下文遷移實(shí)現(xiàn)分布式事務(wù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-10-10.NET 開(kāi)源配置組件 AgileConfig的使用簡(jiǎn)介
這篇文章主要介紹了.NET 開(kāi)源配置組件 AgileConfig的使用簡(jiǎn)介,幫助大家更好的理解和學(xué)習(xí)使用.net技術(shù),感興趣的朋友可以了解下2021-05-05.NET 6開(kāi)發(fā)之實(shí)現(xiàn)緩存過(guò)程詳解
有的時(shí)候?yàn)榱藴p少客戶端請(qǐng)求相同資源的邏輯重復(fù)執(zhí)行,我們會(huì)考慮使用一些緩存的方式。這篇文章主要就介紹了在.NET 6開(kāi)發(fā)中如何實(shí)現(xiàn)緩存,感興趣的可以學(xué)習(xí)一下2022-01-01