ASP.NET MVC3 驗證

今天來看一下在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; }
        }
}

在這裏首先必須引用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; }
       
 }

看到了吧,寫了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;
                }
        }
}

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>

在這裏我對工做年月進行了驗證。固然這是後臺驗證,咱們還須要寫一些前臺驗證的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這樣就完成了先後臺的自定義驗證。
相關文章
相關標籤/搜索