2011-04-16 103 views
1

嗨 我有一個自定義屬性客戶端驗證不工作的自定義屬性

public class NameAttribute : RegularExpressionAttribute 
{ 
    public NameAttribute() : base("abc*") { } 
} 

該工程對服務器端而不是在客戶端,但在這兩者

[RegularExpressionAttribute("abc*",ErrorMessage="asdasd")] 
public String LastName { get; set; } 

作品。我讀了this但它沒有幫助。

我真的很感謝你的幫助。

謝謝

回答

3

您可能需要登記Application_Start關聯到這個自定義屬性DataAnnotationsModelValidatorProvider

protected void Application_Start() 
{ 
    AreaRegistration.RegisterAllAreas(); 
    RegisterRoutes(RouteTable.Routes); 

    DataAnnotationsModelValidatorProvider.RegisterAdapter(
     typeof(NameAttribute), typeof(RegularExpressionAttributeAdapter) 
    ); 
} 

您還可以檢出following blog post

這裏是我用來測試這個完整的例子。

型號:

public class NameAttribute : RegularExpressionAttribute 
{ 
    public NameAttribute() : base("abc*") { } 
} 

public class MyViewModel 
{ 
    [Name(ErrorMessage = "asdasd")] 
    public string LastName { get; set; } 
} 

控制器:

[HandleError] 
public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(new MyViewModel()); 
    } 

    [HttpPost] 
    public ActionResult Index(MyViewModel model) 
    { 
     if (!ModelState.IsValid) 
     { 

     } 
     return View(model); 
    } 
} 

查看:

<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftAjax.js") %>"></script> 
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcAjax.js") %>"></script> 
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcValidation.js") %>"></script> 

<% Html.EnableClientValidation(); %> 
<% using (Html.BeginForm()) { %> 
    <%= Html.LabelFor(x => x.LastName) %> 
    <%= Html.EditorFor(x => x.LastName) %> 
    <%= Html.ValidationMessageFor(x => x.LastName) %> 
    <input type="submit" value="OK" /> 
<% } %> 

加上Application_Start註冊我之前展示。

+0

感謝您的帖子。我希望我能給你更多的不只一分 – David 2011-04-17 18:53:24

相關問題