ASP.NET MVC3 验证

简介:
今天来看一下在ASP.NET MVC中如何实现系统验证和自定义验证。首先来看看我们都需要写哪些东西。


在Models里面我们用了edmx文件,对于我们要验证的字段我们写了部分类进行验证。当然你也可以将edmx生成poco,然后添加验证。我们就看看siteInformation中是如何写的。

InBlock.gif using System; 
InBlock.gif using System.Collections.Generic; 
InBlock.gif using System.Linq; 
InBlock.gif using System.Web; 
InBlock.gif using System.ComponentModel.DataAnnotations; 
InBlock.gif namespace OnlinRegistration.Models 
InBlock.gif
InBlock.gif        [MetadataType( typeof(SiteInformation))] 
InBlock.gif         public partial  class EIF_Sit_Information 
InBlock.gif        { 
InBlock.gif        } 
InBlock.gif 
InBlock.gif         public  sealed  class SiteInformation 
InBlock.gif        { 
InBlock.gif                [Required(AllowEmptyStrings =  false, ErrorMessage =  "毕业院校不能为空")] 
InBlock.gif                [StringLength(32, ErrorMessage =  "毕业院校不能超过32个字符")] 
InBlock.gif                 public  string graduate_school { set; get; } 
InBlock.gif 
InBlock.gif                [Required(AllowEmptyStrings =  false, ErrorMessage =  "证书名称不能为空")] 
InBlock.gif                [StringLength(32, ErrorMessage =  "证书名称不能超过32个字符")] 
InBlock.gif                 public  string certificate_name { set; get; } 
InBlock.gif 
InBlock.gif                [Required(AllowEmptyStrings =  false, ErrorMessage =  "证书编号不能为空")] 
InBlock.gif                [StringLength(32, ErrorMessage =  "证书编号不能超过32个字符")] 
InBlock.gif                 public  string certificate_no { set; get; } 
InBlock.gif 
InBlock.gif                [Required(AllowEmptyStrings =  false, ErrorMessage =  "所学专业不能为空")] 
InBlock.gif                [StringLength(32, ErrorMessage =  "所学专业不能超过16个字符")] 
InBlock.gif                 public  string prefessional { set; get; } 
InBlock.gif 
InBlock.gif                [Required(AllowEmptyStrings =  false, ErrorMessage =  "报考专业不能为空")] 
InBlock.gif                [MaxLength(32, ErrorMessage =  "报考专业代码不能超过32个字符")] 
InBlock.gif                 public  string prefessional_code { set; get; } 
InBlock.gif        } 
InBlock.gif}

在这里首先必须引用System.ComponentModel.DataAnnotations命名空间以及.net Assembly。在这里我们用了自带的一些验证。接下来我们看看自定义验证怎么写。先看一个class
InBlock.gif  public  class Student 
InBlock.gif        { 
InBlock.gif                 public EIF_Student_Registration_Infos studentRegistration { set; get; } 
InBlock.gif                 public EIF_Sit_Information sitInformation { set; get; } 
InBlock.gif 
InBlock.gif                [YearRangeValidation(isValidateEmpty= false)] 
InBlock.gif                [DisplayName( "年份")] 
InBlock.gif                 public  string workYear { set; get; } 
InBlock.gif 
InBlock.gif                [MonthRangeValidation(isValidateEmpty= false)] 
InBlock.gif                [DisplayName( "月份")] 
InBlock.gif                 public  string workMoth { set; get; } 
InBlock.gif       
 }

看到了吧,写了YearRangeValidation和MonthRangeValidation两个自定义验证。我们看看代码

InBlock.gif using System; 
InBlock.gif using System.Collections.Generic; 
InBlock.gif using System.Linq; 
InBlock.gif using System.Web; 
InBlock.gif using System.Web.Mvc; 
InBlock.gif using System.ComponentModel.DataAnnotations; 
InBlock.gif namespace OnlinRegistration.Utility 
InBlock.gif
InBlock.gif        [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple =  true, Inherited =  true)] 
InBlock.gif         public  class YearRangeValidationAttribute : ValidationAttribute, IClientValidatable 
InBlock.gif        { 
InBlock.gif                 public  bool isValidateEmpty { set; get; } 
InBlock.gif                 public YearRangeValidationAttribute() 
InBlock.gif                        :  base( "年份不正确"
InBlock.gif                {} 
InBlock.gif 
InBlock.gif                 public  override  bool IsValid( object value) 
InBlock.gif                { 
InBlock.gif                         if (isValidateEmpty) 
InBlock.gif                        { 
InBlock.gif                                 try 
InBlock.gif                                { 
InBlock.gif                                         int year = Convert.ToInt32(value); 
InBlock.gif                                         return DateTime.Now.AddYears(-100).Year <= year && year <= DateTime.Now.Year; 
InBlock.gif                                } 
InBlock.gif                                 catch 
InBlock.gif                                { 
InBlock.gif                                         return  false
InBlock.gif                                } 
InBlock.gif                        } 
InBlock.gif                         else 
InBlock.gif                        { 
InBlock.gif                                 string year = value  as  string
InBlock.gif                                 if ( string.IsNullOrEmpty(year)) 
InBlock.gif                                { 
InBlock.gif                                         return  true
InBlock.gif                                } 
InBlock.gif                                 else 
InBlock.gif                                { 
InBlock.gif                                         try 
InBlock.gif                                        { 
InBlock.gif                                                 int years = Convert.ToInt32(value); 
InBlock.gif                                                 return DateTime.Now.AddYears(-100).Year <= years && years <= DateTime.Now.Year; 
InBlock.gif                                        } 
InBlock.gif                                         catch 
InBlock.gif                                        { 
InBlock.gif                                                 return  false
InBlock.gif                                        } 
InBlock.gif                                } 
InBlock.gif                        } 
InBlock.gif                } 
InBlock.gif 
InBlock.gif                 public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
InBlock.gif                { 
InBlock.gif                        ModelClientValidationRule rule =  new ModelClientValidationRule 
InBlock.gif                        { 
InBlock.gif                                ValidationType =  "yearrange"
InBlock.gif                                ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()) 
InBlock.gif                        }; 
InBlock.gif                        rule.ValidationParameters.Add( "isvalidateempty", isValidateEmpty); 
InBlock.gif                        yield  return rule; 
InBlock.gif                } 
InBlock.gif        } 
InBlock.gif}

ok这就是要验证年份的验证类。他继承ValidationAttribute属性,实现IClientValidatable接口使得其既可以支持后台验证又可以支持前端验证。
我们看看页面上是如何绑定的。在页面上我绑定的是Student这个类。
InBlock.gif@model OnlinRegistration.Models.Student
< td  style ="background-color: #C4D3FD"  align ="right" > 
                                                                                                参加工作时间: 
                                                                                         </td> 
                                                                                         < td  style ="background-color: #ffffff"  align ="left" > 
                                                                                                @Html.TextBoxFor(stu => stu.workYear, new { style = "width:80px" }) 年 @Html.TextBoxFor(stu => stu.workMoth, new { style = "width:80px" }) 
                                                                                                月 @Html.ValidationMessageFor(stu => stu.workYear) @Html.ValidationMessageFor(stu => stu.workMoth) 
                                                                                         </td>

在这里我对工作年月进行了验证。当然这是后台验证,我们还需要写一些前台验证的js
$.validator.addMethod( "yearrange"function (value, element, param) { 
                         var isValidateEmpty = Boolean.parse(param); 
                         if (isValidateEmpty) { 
                                 var standby = /^\+?[1-9][0-9]*$/; 
                                 return standby.test(value) && parseInt(value) >=  new Date().getFullYear() - 100 && parseInt(value) <=  new Date().getFullYear(); 
                        } 
                         else { 
                                 if (value == "" || value ==  null) { 
                                         return  true
                                } 
                                 else { 
                                         var standby = /^\+?[1-9][0-9]*$/; 
                                         return standby.test(value) && parseInt(value) >=  new Date().getFullYear() - 100 && parseInt(value) <=  new Date().getFullYear(); 
                                } 
                        } 
                }); 
                $.validator.unobtrusive.adapters.addSingleVal( "yearrange""isvalidateempty");

ok这样就实现了前台验证,在前台验证之前你要确保webconfig中的
     < appSettings > 
         < add  key ="webpages:Version"  value ="1.0.0.0"  /> 
         < add  key ="ClientValidationEnabled"  value ="true"  /> 
         < add  key ="UnobtrusiveJavaScriptEnabled"  value ="true"  /> 
         < add  key ="uploadPath"  value ="../../fileUpload"  /> 
     </ appSettings >
ClientValidationEnabled=true和UnobtrusiveJavaScriptEnabled=true。同时注意要引入jquery.validate.min.js,jquery.validate.unobtrusive.min.js,MicrosoftAjax.js,
MicrosoftMvcValidation.js。我们来看看效果



ok这样就完成了前后台的自定义验证。


本文转自 BruceAndLee 51CTO博客,原文链接:http://blog.51cto.com/leelei/638856,如需转载请自行联系原作者

相关文章
|
4天前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
48 0
|
4天前
|
开发框架 前端开发 JavaScript
JavaScript云LIS系统源码ASP.NET CORE 3.1 MVC + SQLserver + Redis医院实验室信息系统源码 医院云LIS系统源码
实验室信息系统(Laboratory Information System,缩写LIS)是一类用来处理实验室过程信息的软件,云LIS系统围绕临床,云LIS系统将与云HIS系统建立起高度的业务整合,以体现“以病人为中心”的设计理念,优化就诊流程,方便患者就医。
23 0
|
4天前
|
开发框架 前端开发 .NET
进入ASP .net mvc的世界
进入ASP .net mvc的世界
32 0
|
4天前
mvc.net分页查询案例——mvc-paper.css
mvc.net分页查询案例——mvc-paper.css
5 0
|
4天前
|
开发框架 前端开发 .NET
C# .NET面试系列六:ASP.NET MVC
<h2>ASP.NET MVC #### 1. MVC 中的 TempData\ViewBag\ViewData 区别? 在ASP.NET MVC中,TempData、ViewBag 和 ViewData 都是用于在控制器和视图之间传递数据的机制,但它们有一些区别。 <b>TempData:</b> 1、生命周期 ```c# TempData 的生命周期是短暂的,数据只在当前请求和下一次请求之间有效。一旦数据被读取,它就会被标记为已读,下一次请求时就会被清除。 ``` 2、用途 ```c# 主要用于在两个动作之间传递数据,例如在一个动作中设置 TempData,然后在重定向到另
122 5
|
4天前
|
XML 前端开发 定位技术
C#(NET Core3.1 MVC)生成站点地图(sitemap.xml)
C#(NET Core3.1 MVC)生成站点地图(sitemap.xml)
33 0
|
4天前
|
前端开发
.net core mvc获取IP地址和IP所在地(其实是百度的)
.net core mvc获取IP地址和IP所在地(其实是百度的)
128 0
|
4天前
|
前端开发
net core mvc获取IP地址和IP所在地(其实是百度的)
net core mvc获取IP地址和IP所在地(其实是百度的)
19 0
|
4天前
|
开发框架 JavaScript .NET
Asp.Net就业课之三验证控件
Asp.Net就业课之三验证控件
45 0
|
6月前
|
开发框架 自然语言处理 前端开发
基于ASP.NET MVC开发的、开源的个人博客系统
基于ASP.NET MVC开发的、开源的个人博客系统
52 0

热门文章

最新文章