1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RegularExpressionAttributeを継承した独自ValidationでClient Validationしたい

1
Posted at

半角英数のみなどの入力チェックをいちいち一からValidationを作るのは面倒。
とはいっても全ての項目にRegularExpressionAttributeをいちいち書くのも面倒。
そんな時、RegularExpressionAttributeを継承した独自Validationを作る場面は良くあると思います。

実際に作ってみると確かにSever Validationは効くのだが、RegularExpressionAttributeで指定したときには効いていたClient Validationが動作しなくなります。

これは、独自Validationサブクラスを作成してプロパティに適用しただけだと、どのClient Validationを適用させるか判別できないためです。
独自ValidationサブクラスをValidatorProviderに登録すれば、Client Validationが動作します。

AlphaNumberAttribute.cs
    /// <summary>
    /// データ フィールドの値が半角英数かを検証する。
    /// </summary>
    {
        public AlphaNumberAttribute() : this(@"[a-zA-Z]+")
        {
        }
        public AlphaNumberAttribute(string pattern) : base(pattern)
        {
            ErrorMessageResourceName = nameof(Resources.Messages.AlphaNumber);
            ErrorMessageResourceType = typeof(Resources.Messages);
        }

    }
Global.asax.cs
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            ModelValidatorAdapterConfig.RegisterModelValidatorAdapters();
        }
    }
ModelValidatorAdapterConfig.cs
    public static class ModelValidatorAdapterConfig
    {
        public static void RegisterModelValidatorAdapters()
        {
            // リソース名の設定
            DefaultModelBinder.ResourceClassKey = nameof(Messages);
            // アダプターの設定
            // 第1引数は独自Validationサブクラス、第2引数はRegularExpressionAttributeAdapter を指定
            DataAnnotationsModelValidatorProvider.RegisterAdapter(
                typeof(AlphaNumberAttribute), typeof(RegularExpressionAttributeAdapter));

        }
    }

元ネタ
Inheriting from RequiredAttribute breaks client side validation on ASP.NET MVC 2 RC.
https://forums.asp.net/t/1528277.aspx?Inheriting+from+RequiredAttribute+breaks+client+side+validation+on+ASP+NET+MVC+2+RC+

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?