.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(, MinimumLength = , ErrorMessage = "姓名的长度为{2}至{1}个字符")]
public string Name { get; set; }

StringLength:字符长度验证,5:表示字符串的最大长度,MinimumLength:表示字符串的最小长度,ErrorMessage:是自定义错误提示信息

  效果如下:

验证Age字段值范围:[Range(18, 60, ErrorMessage = "年龄的范围在{1}至{2}之间")]

[Range(, , 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 > ; }).ToList().FirstOrDefault();
if (ErrorsModel != null)
{
ErrorMsg = ErrorsModel.Errors[].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

C# MVC验证Model的更多相关文章

  1. MVC 3 数据验证 Model Validation 详解

    在MVC 3中 数据验证,已经应用的非常普遍,我们在web form时代需要在View端通过js来验证每个需要验证的控件值,并且这种验证的可用性很低.但是来到了MVC 新时代,我们可以通过MVC提供的 ...

  2. MetadataType的使用,MVC的Model层数据验证

    MetadataType的使用,MVC的Model层数据验证 指定要与数据模型类关联的元数据类   using System.ComponentModel.DataAnnotations; //指定要 ...

  3. (转)MVC 3 数据验证 Model Validation 详解

    继续我们前面所说的知识点进行下一个知识点的分析,这一次我们来说明一下数据验证.其实这是个很容易理解并掌握的地方,但是这会浪费大家狠多的时间,所以我来总结整理一下,节约一下大家宝贵的时间. 在MVC 3 ...

  4. <转>ASP.NET学习笔记之MVC 3 数据验证 Model Validation 详解

    MVC 3 数据验证 Model Validation 详解  再附加一些比较好的验证详解:(以下均为引用) 1.asp.net mvc3 的数据验证(一) - zhangkai2237 - 博客园 ...

  5. MVC验证07-自定义Model级别验证

    原文:MVC验证07-自定义Model级别验证 在一般的自定义验证特性中,我们通过继承ValidationAttribute,实现IClientValidatable,只能完成对某个属性的自定义验证. ...

  6. 【转】METADATATYPE的使用,MVC的MODEL层数据验证

    http://www.cnblogs.com/chshnan/archive/2011/07/08/2100713.html MetadataType的使用,MVC的Model层数据验证指定要与数据模 ...

  7. 任务48:Identity MVC:Model后端验证

    任务48:Identity MVC:Model后端验证 RegisterViewModel using System; using System.Collections.Generic; using ...

  8. 任务49:Identity MVC:Model前端验证

    任务49:Identity MVC:Model前端验证 前端验证使用的是jquery的validate的组件 _ValidationScriptsPartial.cshtml 在我们的layout里面 ...

  9. Asp.net MVC验证哪些事(2)-- 验证规则总结以及使用

    上篇文章Asp.net MVC验证那些事(1)-- 介绍和验证规则使用中,介绍了Asp.net MVC中的验证功能以及如何使用.这里将对MVC中内置的验证规则进行总结. 一,查找所有验证规则 上篇文章 ...

随机推荐

  1. 2.表单与PHP

    不管是一般的企业网站还是复杂的网络应用,都离不开数据的添加.通过PHP服务器端脚本语言,程序可以处理那些通过浏览器对Web应用进行数据调用或添加的请求. 回忆一下平常使用的网站数据输入功能,不管是We ...

  2. cmake安装

    下载之后 1.解压 root@zsh-linux:/opt#tar -zxvf  cmake-2.8.4.tar.gz 2.然后 cd 到cmake-2.8.4目录下  安装 root@zsh-lin ...

  3. Linux一行命令处理批量文件

    前言 最好的方法不一定是你最快能想到的.这里提供一种使用sed命令构造命令解决处理批量文件的技巧,供参考. 需求案例1 将当前目录下所有的0_80_91.txt.0_80_92.txt.0_80_93 ...

  4. CentOS6.3上安装与配置nginx+php+mysql环境

    1. 目前nginx采用是源码包安装的方式(yum安装失败),下载地址:http://nginx.org/en/download.html 我这里的安装包是:nginx-1.12.0.tar.gz 2 ...

  5. Version Control/Git,SVN

    一.Version Control 1.什么是Version Control 版本控制(Version Control)是指对软件开发过程中各种程序代码.配置文件及说明文档等文件变更的管理,是软件配置 ...

  6. 知识点---前端处理支持emoji表情

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. 定时器&改变定时器的执行频率

    static System.Threading.Timer timer; static void Main(string[] args) { Console.WriteLine("Press ...

  8. bootstrap日期选择

    <input type="text" class="form-control datepicker" style="padding: 0.375 ...

  9. python_Tkinter

    Tkinter相关 python支持多种图形界面的第三方库,包括:TKwxWidgetsQTGTK等等但是python自带的库是支持TK的TKinter,使用使用Tkinter,无需安装任何包,就可以 ...

  10. 关于STM32CubeMX使用LL库设置PWM输出

    HAL和LL库 HAL是ST为了实现代码在ST家族的MCU上的移植性,推出的一个库,称为硬件抽象层,很明显,这样做将会牺牲存储资源,所以项目最后的代码比较冗余,且运行效率大大降低,运行速度受制于fla ...