MVC 数据验证
控制器 Home
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcApplication2.Models; namespace MvcApplication2.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { return View(); } /// <summary> /// 检查用户名是否有重复 /// </summary> /// <param name="userName">用户在页面(视图)表单中输入的UserName</param> /// <returns>Json</returns> public ActionResult CheckUserName(string userName) { bool result = false; using (var datas = new salesEntities()) { var query = from userinfo in datas.T_UserInfo where userinfo.Name == userName select new { Name= userinfo.Name }; if (query == null || !query.Any()) { result = true; } } return Json(result,JsonRequestBehavior.AllowGet); } } }
Model(UserInfo)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace MvcApplication2.Models { /// <summary> /// 这些例子就是验证的,注意此处没有客户端验证,完全是服务器端验证的,如果出错,视图会渲染再次显示,非常好用啊,很方便啊,要在以前你要写多少行代码来搞定这些繁琐无味的验证呢?微软太体恤程序员了,顶一个。 /// 在下面的例子当中,当数据发送到服务器验证不通过之后,则所有用户填写的内容在重新打开的页面后都清空了, 如果想不清空,即用户第一次填的内容还存在的话,可以return View(接受到的对象); /// </summary> public class UserInfo { public int Id { get; set; } //ID /// <summary> ///DisplayName:指定当前字段显示的名称 ///StringLength:指定允许的长度,括号里的第一个参数是最大长度,第二个参数是最小长度。最后一个参数是指:单字段值的长度不符合第一第二参数规定时候,提示错误的内容 ///Required:表示当前字段是必填选项,当提交的表单缺少该值就引发验证错误。括号里的AllowEmptyStrings是: 获取或设置一个值,该值指示是否允许空字符串。单值为false的时候表示当前字段的值不能为空 ///Remote:允许利用服务器端的回调函数执行客户端的验证逻辑。说白了就是支持AJAX验证。括号里的CheckUserName是Action方法。Home是控制器 /// </summary> [DisplayName("用户名")] [Required(AllowEmptyStrings=false, ErrorMessage="用户名不能为空")] [StringLength(10,MinimumLength=2,ErrorMessage="用户名长度不能大于{2}且要小于{1}")] [Remote("CheckUserName", "Home", ErrorMessage = "用户名已经存在")] public string UserName { get; set; } //用户名 [DisplayName("用户密码")] [DataType(DataType.Password)] //将密码已*号的形式来显示 [Required(AllowEmptyStrings=false,ErrorMessage="密码不能为空")] [StringLength(12,MinimumLength=6,ErrorMessage="密码必须在{2}和{1}之间")] public string UserPassword { get; set; } //用户密码 [DataType(DataType.Password)] [Compare("UserPassword",ErrorMessage="密码不一致")] [DisplayName("请再次确认密码")] public string TUserPassword{get;set;} //再次输出密码 /// <summary> /// RegularExpression:表示当前字段的值要符合一个正则表达式。如果不能匹配,则报一个验证错误。ErrorMessage的内容就是验证错误的具体信息。 /// </summary> [Display(Name = "邮箱")] //也可以写成 [DisplayName("邮箱")] [Required(AllowEmptyStrings=false,ErrorMessage="邮箱不能为空")] [DataType(DataType.EmailAddress,ErrorMessage="请输入有效的邮箱地址")] //其实也可以用以下的正则表达式来验证邮箱 //[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9]+\.[A-Za-z]{2,4}", ErrorMessage = "{0}的格式不正确")] public string Email { get; set; } //邮箱 [DisplayName("请再次确认邮箱")] [Compare("Email",ErrorMessage="两次输入的邮箱不一致")] //[DataType(DataType.EmailAddress, ErrorMessage = "请输入有效的邮箱地址")] public string TEmail { get; set; } //再次输入邮箱 [DisplayName("身份证")] [RegularExpression(@"\d{17}[\d|x]|\d{15}", ErrorMessage = "身份证号码格式错误")] public string IdentityNo { get; set; } //身份证号 /// <summary> /// Range:用来指定数值类型值的最小值和最大值。括号里的第一个数的“最小值”第二个参数是“最大值” /// </summary> [DisplayName("年龄")] [Required(AllowEmptyStrings=false,ErrorMessage="年龄不能为空")] [Range(10,150,ErrorMessage="年龄不能大于{2},且不能小于{1}")] public int Age { get; set; } //年龄 /// <summary> /// DisplayFormat:用来处理属性的各种格式化选项。当属性包含空值时,可以提供可选的显示文本,也可以为包含标记的属性关闭HTML编码,还可以为运行时指定一个应用于属性值的格式化字符串。 /// </summary> [DisplayName("金额")] [DataType(DataType.Currency)] //Currency:表示货币值 [DisplayFormat(ApplyFormatInEditMode=true,DataFormatString="{0:c}")] [Required(ErrorMessage = "金额不能为空")] [Range(typeof(decimal), "20.0", "30.0", ErrorMessage = "金额在{1}和{2}之间")] public decimal Money { get; set; } //金额 [Display(Name="手机号码")] //[DataType(DataType.PhoneNumber)] [RegularExpression(@"((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)", ErrorMessage = "格式不正确")] public int Phome { get; set; } [Display(Name="生日")] //[DisplayFormat(ApplyFormatInEditMode=true,DataFormatString="yyyy/MM/dd")] [Required] //当前字段的值不能为空 public DateTime Birthday { get; set; } //生日 [Display(Name="备注")] [DataType(DataType.MultilineText)] //当前字段是个多行文本 public string Remarks { get; set; } //备注 } }
View (Index)
@model MvcApplication2.Models.UserInfo @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <script src="~/Scripts/jquery-1.7.1.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>UserInfo</legend> <div class="editor-label"> @Html.LabelFor(model => model.UserName) </div> <div class="editor-field"> @Html.EditorFor(model => model.UserName) @Html.ValidationMessageFor(model => model.UserName) </div> <div class="editor-label"> @Html.LabelFor(model => model.UserPassword) </div> <div class="editor-field"> @Html.EditorFor(model => model.UserPassword) @Html.ValidationMessageFor(model => model.UserPassword) </div> <div class="editor-label"> @Html.LabelFor(model => model.TUserPassword) </div> <div class="editor-field"> @Html.EditorFor(model => model.TUserPassword) @Html.ValidationMessageFor(model => model.TUserPassword) </div> <div class="editor-label"> @Html.LabelFor(model => model.Email) </div> <div class="editor-field"> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <div class="editor-label"> @Html.LabelFor(model => model.TEmail) </div> <div class="editor-field"> @Html.EditorFor(model => model.TEmail) @Html.ValidationMessageFor(model => model.TEmail) </div> <div class="editor-label"> @Html.LabelFor(model => model.IdentityNo) </div> <div class="editor-field"> @Html.EditorFor(model => model.IdentityNo) @Html.ValidationMessageFor(model => model.IdentityNo) </div> <div class="editor-label"> @Html.LabelFor(model => model.Age) </div> <div class="editor-field"> @Html.EditorFor(model => model.Age) @Html.ValidationMessageFor(model => model.Age) </div> <div class="editor-label"> @Html.LabelFor(model => model.Money) </div> <div class="editor-field"> @Html.EditorFor(model => model.Money) @Html.ValidationMessageFor(model => model.Money) </div> <div class="editor-label"> @Html.LabelFor(model => model.Phome) </div> <div class="editor-field"> @Html.EditorFor(model => model.Phome) @Html.ValidationMessageFor(model => model.Phome) </div> <div class="editor-label"> @Html.LabelFor(model => model.Birthday) </div> <div class="editor-field"> @Html.EditorFor(model => model.Birthday) @Html.ValidationMessageFor(model => model.Birthday) </div> <div class="editor-label"> @Html.LabelFor(model => model.Remarks) </div> <div class="editor-field"> @Html.EditorFor(model => model.Remarks) @Html.ValidationMessageFor(model => model.Remarks) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> </body> </html>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。