.NET Core MVC3 數據模型驗證的使用
這里我先粘貼一個已經加了數據驗證的實體類PeopleModel,然后一一介紹。
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Model實體數據驗證.Model
{
/// <summary>
/// 這里將指定PeopleModel自身的Required、StringLength等驗證通過后,再進行PeopleModelVaildation中的CheckModel驗證
/// </summary>
[CustomValidation(typeof(PeopleModelVaildation), "CheckModel")]
public class PeopleModel
{
/// <summary>
/// 姓名
/// </summary>
[Required(ErrorMessage = "姓名不能為空")]
[StringLength(5, MinimumLength = 2, ErrorMessage = "姓名的長度為{2}至{1}個字符")]
public string Name { get; set; }
/// <summary>
/// 年齡
/// </summary>
[Required(ErrorMessage = "年齡不能為空")]
[Range(18, 60, ErrorMessage = "年齡的范圍在{1}至{2}之間")]
public string Age { get; set; }
/// <summary>
/// 性別
/// </summary>
[Required(ErrorMessage = "性別不能為空")]
public string Gender { get; set; }
/// <summary>
/// 生日
/// </summary>
[Required(ErrorMessage = "生日不能為空")]
public DateTime Brithday { get; set; }
}
/// <summary>
/// 這個驗證在實體內部的驗證通過后,才會執行
/// </summary>
public class PeopleModelVaildation
{
public static ValidationResult CheckModel(object value, ValidationContext validationContext)
{
///如果value是PeopleModel的實體類型,則驗證value中指定的數據類型。
if (value is PeopleModel item) {
///驗證生日
if (item.Brithday>DateTime.Now) {
return new ValidationResult("生日信息錯誤");
}
}
//驗證成功
return ValidationResult.Success;
}
}
}
我們需要在實體類中引入命名空間:using System.ComponentModel.DataAnnotations
驗證Name字段不能為空:[Required(ErrorMessage = "姓名不能為空")]
/// <summary> /// 姓名 /// </summary> [Required(ErrorMessage = "姓名不能為空")] public string Name { get; set; }
Required:非空驗證,ErrorMessage:是自定義錯誤提示信息
效果如下:

驗證Name字段字符長度:[StringLength(5, MinimumLength = 2, ErrorMessage = "姓名的長度為{2}至{1}個字符")]
[StringLength(5, MinimumLength = 2, ErrorMessage = "姓名的長度為{2}至{1}個字符")] public string Name { get; set; }
StringLength:字符長度驗證,5:表示字符串的最大長度,MinimumLength:表示字符串的最小長度,ErrorMessage:是自定義錯誤提示信息
效果如下:

驗證Age字段值范圍:[Range(18, 60, ErrorMessage = "年齡的范圍在{1}至{2}之間")]
[Range(18, 60, ErrorMessage = "年齡的范圍在{1}至{2}之間")] public string Age { get; set; }
Range:驗證字符取值范圍,18:表示最小年齡,60:表示最大年齡,ErrorMessage:是自定義錯誤提示信息
效果如下:


驗證兩次密碼輸入是否相同(比如用戶修改密碼時,需要驗證用戶兩次輸入的新密碼是否一致):[Compare("PwdOne", ErrorMessage = "兩次密碼輸入不一致")]
/// <summary> /// 第一次輸入的密碼 /// </summary> public string PwdOne { get; set; } /// <summary> /// 第二次輸入的密碼 /// </summary> [Compare("PwdOne", ErrorMessage = "兩次密碼輸入不一致")] public string PwdTwo { get; set; }
Compare:驗證兩個字段內容是否相同,"PwdOne":需要數據對比的字段名,ErrorMessage:是自定義錯誤提示信息
下面我們新建一個ModelFilter過濾器並繼承ActionFilterAttribute,用來接收實體類中的ErrorMessage信息,並返回給客服端
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Model實體數據驗證.Common { /// <summary> /// 實體驗證過濾器 /// 需要在Starup.cs中的ConfigureServices中注冊 /// </summary> public class ModelFilter:ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { if (!context.ModelState.IsValid) { ///實體驗證未通過 string ErrorMsg = string.Empty; var ErrorsModel = context.ModelState.Values.Where(item => { return item.Errors.Count > 0; }).ToList().FirstOrDefault(); if (ErrorsModel != null) { ErrorMsg = ErrorsModel.Errors[0].ErrorMessage; } context.Result = new JsonResult(ErrorMsg); return; } } } }
這里還需要給ModelFilter過濾器類在Startup.cs類中注入服務,具體代碼如下:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Model實體數據驗證.Common; namespace Model實體數據驗證 { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); //給ModelFilter注入服務 services.AddMvc(filter=>filter.Filters.Add<ModelFilter>()); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(routes=> { routes.MapRoute( name:"default", template:"{controller=Home}/{action=Index}/{id?}" ); }); } } }
HomeController代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Model實體數據驗證.Model; namespace Model實體數據驗證.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } [HttpPost] public IActionResult Add(PeopleModel model) { return Json("驗證成功"); } } }
Html代碼:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> <label>姓名:</label> <br /> <input type="text" id="Name"/> <br /> <br /> <label>年齡:</label> <br /> <input type="text" id="Age"/> <br /> <br /> <label>性別:</label> <br /> <input type="text" id="Gender"/> <br /> <br /> <label>生日:</label> <br /> <input type="text" id="Brithday"/> <br /> <br /> <button type="button" id="submit">提交</button> </div> <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> $("#submit").click(function () { $(function () { var data = {}; data.Name = $("#Name").val(); data.Age = $("#Age").val(); data.Gender = $("#Gender").val(); data.Brithday = $("#Brithday").val(); $.ajax({ type: "POST", url: "/Home/Add", dataType: "JSON", data: data, success: function (obj) { alert(obj); }, error: function (er) { console.log(er); } }); }); }); </script> </body> </html>
現在來看下效果:

Demo下載地址:https://pan.baidu.com/s/1NZ68edipDOvNKmMWXb0rgg
密碼:072d
