今天来看一下在ASP.NET MVC中如何实现系统验证和自定义验证。首先来看看我们都需要写哪些东西。
在Models里面我们用了edmx文件,对于我们要验证的字段我们写了部分类进行验证。当然你也可以将edmx生成poco,然后添加验证。我们就看看siteInformation中是如何写的。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace OnlinRegistration.Models
{
[MetadataType( typeof(SiteInformation))]
public partial class EIF_Sit_Information
{
}
public sealed class SiteInformation
{
[Required(AllowEmptyStrings = false, ErrorMessage = "毕业院校不能为空")]
[StringLength(32, ErrorMessage = "毕业院校不能超过32个字符")]
public string graduate_school { set; get; }
[Required(AllowEmptyStrings = false, ErrorMessage = "证书名称不能为空")]
[StringLength(32, ErrorMessage = "证书名称不能超过32个字符")]
public string certificate_name { set; get; }
[Required(AllowEmptyStrings = false, ErrorMessage = "证书编号不能为空")]
[StringLength(32, ErrorMessage = "证书编号不能超过32个字符")]
public string certificate_no { set; get; }
[Required(AllowEmptyStrings = false, ErrorMessage = "所学专业不能为空")]
[StringLength(32, ErrorMessage = "所学专业不能超过16个字符")]
public string prefessional { set; get; }
[Required(AllowEmptyStrings = false, ErrorMessage = "报考专业不能为空")]
[MaxLength(32, ErrorMessage = "报考专业代码不能超过32个字符")]
public string prefessional_code { set; get; }
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace OnlinRegistration.Models
{
[MetadataType( typeof(SiteInformation))]
public partial class EIF_Sit_Information
{
}
public sealed class SiteInformation
{
[Required(AllowEmptyStrings = false, ErrorMessage = "毕业院校不能为空")]
[StringLength(32, ErrorMessage = "毕业院校不能超过32个字符")]
public string graduate_school { set; get; }
[Required(AllowEmptyStrings = false, ErrorMessage = "证书名称不能为空")]
[StringLength(32, ErrorMessage = "证书名称不能超过32个字符")]
public string certificate_name { set; get; }
[Required(AllowEmptyStrings = false, ErrorMessage = "证书编号不能为空")]
[StringLength(32, ErrorMessage = "证书编号不能超过32个字符")]
public string certificate_no { set; get; }
[Required(AllowEmptyStrings = false, ErrorMessage = "所学专业不能为空")]
[StringLength(32, ErrorMessage = "所学专业不能超过16个字符")]
public string prefessional { set; get; }
[Required(AllowEmptyStrings = false, ErrorMessage = "报考专业不能为空")]
[MaxLength(32, ErrorMessage = "报考专业代码不能超过32个字符")]
public string prefessional_code { set; get; }
}
}
在这里首先必须引用System.ComponentModel.DataAnnotations命名空间以及.net Assembly。在这里我们用了自带的一些验证。接下来我们看看自定义验证怎么写。先看一个class
public
class Student
{
public EIF_Student_Registration_Infos studentRegistration { set; get; }
public EIF_Sit_Information sitInformation { set; get; }
[YearRangeValidation(isValidateEmpty= false)]
[DisplayName( "年份")]
public string workYear { set; get; }
[MonthRangeValidation(isValidateEmpty= false)]
[DisplayName( "月份")]
public string workMoth { set; get; }
{
public EIF_Student_Registration_Infos studentRegistration { set; get; }
public EIF_Sit_Information sitInformation { set; get; }
[YearRangeValidation(isValidateEmpty= false)]
[DisplayName( "年份")]
public string workYear { set; get; }
[MonthRangeValidation(isValidateEmpty= false)]
[DisplayName( "月份")]
public string workMoth { set; get; }
}
看到了吧,写了YearRangeValidation和MonthRangeValidation两个自定义验证。我们看看代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace OnlinRegistration.Utility
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class YearRangeValidationAttribute : ValidationAttribute, IClientValidatable
{
public bool isValidateEmpty { set; get; }
public YearRangeValidationAttribute()
: base( "年份不正确")
{}
public override bool IsValid( object value)
{
if (isValidateEmpty)
{
try
{
int year = Convert.ToInt32(value);
return DateTime.Now.AddYears(-100).Year <= year && year <= DateTime.Now.Year;
}
catch
{
return false;
}
}
else
{
string year = value as string;
if ( string.IsNullOrEmpty(year))
{
return true;
}
else
{
try
{
int years = Convert.ToInt32(value);
return DateTime.Now.AddYears(-100).Year <= years && years <= DateTime.Now.Year;
}
catch
{
return false;
}
}
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule rule = new ModelClientValidationRule
{
ValidationType = "yearrange",
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
};
rule.ValidationParameters.Add( "isvalidateempty", isValidateEmpty);
yield return rule;
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
namespace OnlinRegistration.Utility
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class YearRangeValidationAttribute : ValidationAttribute, IClientValidatable
{
public bool isValidateEmpty { set; get; }
public YearRangeValidationAttribute()
: base( "年份不正确")
{}
public override bool IsValid( object value)
{
if (isValidateEmpty)
{
try
{
int year = Convert.ToInt32(value);
return DateTime.Now.AddYears(-100).Year <= year && year <= DateTime.Now.Year;
}
catch
{
return false;
}
}
else
{
string year = value as string;
if ( string.IsNullOrEmpty(year))
{
return true;
}
else
{
try
{
int years = Convert.ToInt32(value);
return DateTime.Now.AddYears(-100).Year <= years && years <= DateTime.Now.Year;
}
catch
{
return false;
}
}
}
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule rule = new ModelClientValidationRule
{
ValidationType = "yearrange",
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
};
rule.ValidationParameters.Add( "isvalidateempty", isValidateEmpty);
yield return rule;
}
}
}
ok这就是要验证年份的验证类。他继承ValidationAttribute属性,实现IClientValidatable接口使得其既可以支持后台验证又可以支持前端验证。
我们看看页面上是如何绑定的。在页面上我绑定的是Student这个类。
@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>
参加工作时间:
</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");
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中的
ClientValidationEnabled=true和UnobtrusiveJavaScriptEnabled=true。同时注意要引入jquery.validate.min.js,jquery.validate.unobtrusive.min.js,MicrosoftAjax.js,
<
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 >
< 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 >
MicrosoftMvcValidation.js。我们来看看效果
ok这样就完成了前后台的自定义验证。
本文转自 BruceAndLee 51CTO博客,原文链接:http://blog.51cto.com/leelei/638856,如需转载请自行联系原作者