半角英数のみなどの入力チェックをいちいち一からValidationを作るのは面倒。
とはいっても全ての項目にRegularExpressionAttributeをいちいち書くのも面倒。
そんな時、RegularExpressionAttributeを継承した独自Validationを作る場面は良くあると思います。
実際に作ってみると確かにSever Validationは効くのだが、RegularExpressionAttributeで指定したときには効いていたClient Validationが動作しなくなります。
これは、独自Validationサブクラスを作成してプロパティに適用しただけだと、どのClient Validationを適用させるか判別できないためです。
独自ValidationサブクラスをValidatorProviderに登録すれば、Client Validationが動作します。
/// <summary>
/// データ フィールドの値が半角英数かを検証する。
/// </summary>
{
public AlphaNumberAttribute() : this(@"[a-zA-Z]+")
{
}
public AlphaNumberAttribute(string pattern) : base(pattern)
{
ErrorMessageResourceName = nameof(Resources.Messages.AlphaNumber);
ErrorMessageResourceType = typeof(Resources.Messages);
}
}
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();
}
}
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+