博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET MVC3 验证
阅读量:6094 次
发布时间:2019-06-20

本文共 4844 字,大约阅读时间需要 16 分钟。

今天来看一下在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,如需转载请自行联系原作者
你可能感兴趣的文章
公式推♂倒题
查看>>
vue实现点击展开,点击收起
查看>>
如何使frame能居中显示
查看>>
第k小数
查看>>
构建之法阅读笔记三
查看>>
Python/PHP 远程文件/图片 下载
查看>>
【原创】一文彻底搞懂安卓WebView白名单校验
查看>>
写给对前途迷茫的朋友:五句话定会改变你的人生
查看>>
并行程序设计学习心得1——并行计算机存储
查看>>
JAVA入门到精通-第86讲-半双工/全双工
查看>>
bulk
查看>>
js document.activeElement 获得焦点的元素
查看>>
abb画学号
查看>>
C++ 迭代器运算
查看>>
【支持iOS11】UITableView左滑删除自定义 - 实现多选项并使用自定义图片
查看>>
day6-if,while,for的快速掌握
查看>>
JavaWeb学习笔记(十四)--JSP语法
查看>>
【算法笔记】多线程斐波那契数列
查看>>
java8函数式编程实例
查看>>
jqgrid滚动条宽度/列显示不全问题
查看>>