转载请注明出处:http://www.cnblogs.com/zhiyong-ITNote/

官方网站:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/models/validation?view=aspnetcore-2.1

首先派生自ValidationAttribute以及IClientModelValidator:

public class ClassicMovieAttribute : ValidationAttribute, IClientModelValidator
{
private int _year; public ClassicMovieAttribute(int Year)
{
_year = Year;
} protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
Movie movie = (Movie)validationContext.ObjectInstance; if (movie.Genre == Genre.Classic && movie.ReleaseDate.Year > _year)
{
return new ValidationResult(GetErrorMessage());
} return ValidationResult.Success;
} public void AddValidation(ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
} MergeAttribute(context.Attributes, "data-val", "true");
MergeAttribute(context.Attributes, "data-val-classicmovie", GetErrorMessage()); var year = _year.ToString(CultureInfo.InvariantCulture);
MergeAttribute(context.Attributes, "data-val-classicmovie-year", year);
} private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
{
if (attributes.ContainsKey(key))
{
return false;
} attributes.Add(key, value);
return true;
} private string GetErrorMessage()
{
return $"Classic movies must have a release year earlier than {_year}.";
}
}

创建两个类:

创建两个类:
public class Movie
{
public int Id { get; set; } [Required]
[StringLength()]
public string Title { get; set; } [ClassicMovie()]
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; } [Required]
[StringLength()]
public string Description { get; set; } [Range(, 999.99)]
public decimal Price { get; set; } [Required]
public Genre Genre { get; set; } public bool Preorder { get; set; }
} public enum Genre
{
Classic,
PostClassic,
Modern,
PostModern,
Contemporary,
}

视图方面:

<form asp-action="Create">
<div class="form-horizontal">
<h4>Movie</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Title" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="ReleaseDate" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="ReleaseDate" class="form-control" />
<span asp-validation-for="ReleaseDate" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Description" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Description" class="form-control" />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Price" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Genre" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="Genre" asp-items="@(Html.GetEnumSelectList<Genre>())" class="form-control"></select>
<span asp-validation-for="Genre" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
<input asp-for="Preorder" />
<label asp-for="Preorder"></label>
</div>
</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>
</form> @section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");} <script type="text/javascript">
$(function () {
$.validator.addMethod('classicmovie',
function (value, element, params) {
// Get element value. Classic genre has value '0'.
var genre = $(params[]).val(),
year = params[],
date = new Date(value);
if (genre && genre.length > && genre[] === '') {
// Since this is a classic movie, invalid if release date is after given year.
return date.getFullYear() <= year;
} return true;
}); $.validator.unobtrusive.adapters.add('classicmovie',
['year'],
function (options) {
var element = $(options.form).find('select#Genre')[];
options.rules['classicmovie'] = [element, parseInt(options.params['year'])];
options.messages['classicmovie'] = options.message;
});
});
</script>
} 然后创建一个Action:
public IActionResult Index(Movie movie)
{
if(ModelState.isValid)
{
return Content("dsadas");
}
return View();
}

然后创建一个Action:

public IActionResult Index(Movie movie)
{
if(ModelState.isValid)
{
return Content("dsadas");
}
return View();
}

我们可以在qq浏览器中的查看页面源代码,会给我们生成:

<input class="form-control" type="datetime"
data-val="true"
data-val-classicmovie="Classic movies must have a release year earlier than 1960."
data-val-classicmovie-year="1960"
data-val-required="The ReleaseDate field is required."
id="ReleaseDate" name="ReleaseDate" value="" />

也就是说,浏览器已经给我们解析好了,这样我们就可以一次比较,前后端验证。当然我们也可以使用bootstrapValidator验证。

转载请注明出处:http://www.cnblogs.com/zhiyong-ITNote/

asp.net core自定义模型验证——前端验证的更多相关文章

  1. ASP.NET Core WebApi中使用FluentValidation验证数据模型

    原文链接:Common features in ASP.NET Core 2.1 WebApi: Validation 作者:Anthony Giretti 译者:Lamond Lu 介绍 验证用户输 ...

  2. asp.net MVC 自定义模型绑定 从客户端中检测到有潜在危险的 Request.QueryString 值

    asp.net mvc 自定义模型绑定 有潜在的Requset.Form 自定义了一个模型绑定器.前端会传过来一些敏感字符.调用bindContext. valueProvider.GetValue( ...

  3. asp.net core 自定义认证方式--请求头认证

    asp.net core 自定义认证方式--请求头认证 Intro 最近开始真正的实践了一些网关的东西,最近写几篇文章分享一下我的实践以及遇到的问题. 本文主要介绍网关后面的服务如何进行认证. 解决思 ...

  4. ASP.NET CORE 管道模型及中间件使用解读

    说到ASP.NET CORE 管道模型不得不先来看看之前的ASP.NET 的管道模型,两者差异很大,.NET CORE 3.1 后完全重新设计了框架的底层,.net core 3.1 的管道模型更加灵 ...

  5. asp.net core自定义端口

    asp.net Core 自定义端口 官方文档 aspnet内库源码: https://github.com/aspnet dotnet系统内库源码:https://github.com/dotnet ...

  6. ASP.NET Core微服务+Tabler前端框架搭建个人博客1--开始前想说的话

    写在前面 本人为在读研究生,特别喜欢.NET,觉得.NET的编程方式.语法都特别友好,学习.NET Core已经差不多有一年半了,从一开始不知道如何入门到现在终于可以编写一些小的应用程序,想一想还是非 ...

  7. asp.net mvc 自定义模型绑定

    在asp.net mvc的控制器中如果能够活用模型的自动绑定功能的话能够减少许多工作量.但是如果我们想要对前台传来的数据进行一些处理再绑定到模型上,该怎么做呢? 这里用一个绑定用户数据的小案例来讲解a ...

  8. 如何在ASP.NET Core自定义中间件中读取Request.Body和Response.Body的内容?

    原文:如何在ASP.NET Core自定义中间件中读取Request.Body和Response.Body的内容? 文章名称: 如何在ASP.NET Core自定义中间件读取Request.Body和 ...

  9. asp.net core 自定义异常处理中间件

    asp.net core 自定义异常处理中间件 Intro 在 asp.net core 中全局异常处理,有时候可能不能满足我们的需要,可能就需要自己自定义一个中间件处理了,最近遇到一个问题,有一些异 ...

随机推荐

  1. verilog 异步复位代码

    module reset_sync (input clk, input reset_in, output reset_out); (* ASYNC_REG = 'b1; (* ASYNC_REG = ...

  2. LeetCode(84): 柱状图中最大的矩形

    Hard! 题目描述: 给定 n 个非负整数,用来表示柱状图中各个柱子的高度.每个柱子彼此相邻,且宽度为 1 . 求在该柱状图中,能够勾勒出来的矩形的最大面积. 以上是柱状图的示例,其中每个柱子的宽度 ...

  3. kali linux 更新问题

    1.使用一次更新和升级软件替换 apt-get install && apt -y full -upgrade 之后使用 reboot重启    系统,重启之后 再次使用命令   ap ...

  4. Spring Boot如何使用Runner实现启动时调用?用法和原理都在这里

    在日常的项目开发中经常会遇到这样的需求:项目启动的时候进行一些一次性的初始化工作,如读取加载资源文件.或者执行其它外部程序. 这个时候我们就可以用到spring-boot为我们提供的一种扩展机制--R ...

  5. Python if __name__ == '__main__':(以主程序形式执行)

    在外部调用某个模块时,可能会将只能在本模块执行的代码给执行了,有没有什么办法让某些特定的代码指定只能在自身运行时才执行被调用时不执行呢?使用if __name__ == '__main__':. 示例 ...

  6. MySQL源码安装一键脚本

    #红色部分根据自己的需求来定义#!/bin/bash #卸载系统自带的Mysql /bin/rpm -e $(/bin/rpm -qa | grep mysql|xargs) --nodeps /bi ...

  7. 获取访问IP

    public static String GetIP() { String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_ ...

  8. springboot的创建

  9. python练习册0005

    第 0005 题:你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone5 分辨率的大小. 本题用了几个os模块的命令, import os from PIL import Image p ...

  10. BootStrap标题制作模板

    <!DOCTYPE html><html lang="zh-CN"> <head> <meta charset="UTF-8&q ...