[C#][ASP.NET MVC]Validation Framework-xVal

  • 3888
  • 0
  • C#
  • 2010-03-03

[C#][ASP.NET MVC]Validation Framework-xVal

之前自己實做了Validation,之後逛codeplex讓我發現了還滿不錯的Validation Framework-xVal

 

相關特性

image

xVal最大特性就是可以將server端和client端的驗證機制連結起來,

廢話不多說,馬上實作client-side validation體驗看看(server-side方法和Data Annotation Validators大同小異)

 

xVal前置步驟

1.Master Page加入xVal相關Scripts(only support jquery-1.2.6.js )

<script type="text/javascript" src="../../Scripts/jquery-1.2.6.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.validate.js">
</script> <script type="text/javascript" src="../../Scripts/xVal.jquery.validate.js"></script>

2.修改web.config

<pages>
     <namespaces>
        <!-- leave rest as-is -->
        <add namespace="xVal.Html"/>
    </namespaces>
  </pages>
 

 Add Models(PersonRepository)

using System.ComponentModel.DataAnnotations;
 
 public class PersonRepository
    {
        [Required( ErrorMessage = "姓名必填" )]
        public String Name
        {
            get;
            set;
        }
 
        [Required( ErrorMessage = "住址必填" )]
        public String Address
        {
            get;
            set;
        }
 
        [Range( 1, 99, ErrorMessage = "不可以大於99" )]
        public Int32 Age
        {
            get;
            set;
        }
    }

 Add DataAnnotationsValidationRunner.cs(直接使用作者所提供的class)

Add PersonManager.cs
public class PersonManager
    {
        public static void PersonValiation( PersonRepository personrepository )
        {
            var errors = DataAnnotationsValidationRunner.GetErrors( personrepository );
            if( errors.Any() )
            {
                throw new RulesException( errors );                
            }           
        }          
    }

 Add Controle

 public ActionResult PersonCreate()
        {
            return View();
        }
 
        [AcceptVerbs( HttpVerbs.Post )]
        public ActionResult PersonCreate( PersonRepository personrepository )
        {
            try
            {
                PersonManager.PersonValiation( personrepository );            
            }
            catch( RulesException ex )
            {
                ex.AddModelStateErrors( ModelState, "personrepository" );
            }
 
            return ModelState.IsValid ? RedirectToAction( "PersonCreate" )
                                      : ( ActionResult ) View();
        }
 
View的部分直接建立強型別即可。
image 
 
View並增加Html.ClientSideValidation
....
......
<p>
   <input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<%= Html.ClientSideValidation<PersonRepository>( "personrepository" )%>
 
 
執行畫面
先檢視原始碼發現xVal Framework自動產生client script。
image 
image image 
xVal Framework真是方便阿,大家可以玩玩看。 

 

參考:

http://blog.stevensanderson.com/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/

http://xval.codeplex.com/