简体   繁体   English

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

[英]Client Side Validation Not working for custom Attribute

Hi I have a custom Attribute 嗨,我有一个自定义属性

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

This works on the serverside but not in the client side but this 这适用于服务器端,但不适用于客户端,但这样

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

works on both. 适用于两者。 I read this but it does'nt help. 我看了这个,但它没有帮助。

I would really appreciate your assistance. 我非常感谢你的帮助。

Thank you 谢谢

You might need to register a DataAnnotationsModelValidatorProvider associated to this custom attribute in Application_Start : 您可能需要在Application_Start注册与此自定义属性关联的DataAnnotationsModelValidatorProvider

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

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

You might also checkout the following blog post . 您还可以查看以下博客文章

And here's the full example I used to test this. 这是我用来测试这个的完整例子。

Model: 模型:

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);
    }
}

View: 视图:

<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" />
<% } %>

Plus the Application_Start registration I showed earlier. 加上我之前展示的Application_Start注册。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM