Skip to main content
 首页 » 编程设计

c#之客户端验证不适用于自定义属性

2024年02月23日14kuangbin

嗨 我有一个自定义属性

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

这适用于服务器端但不适用于客户端

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

两者都适用。我读了this但这没有帮助。

非常感谢您的帮助。

谢谢

请您参考如下方法:

您可能需要在 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; } 
} 

Controller :

[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 注册。