MVCのカスタム検証属性を作成する方法
-
24-09-2019 - |
質問
RegularexpressionAttributeから継承しないが、クライアントの検証で使用できる電子メールアドレスのMVC2のカスタム検証属性を作成したいと思います。誰かが私を正しい方向に向けることができますか?
私はこれほど単純なことを試しました:
[AttributeUsage( AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false )]
public class EmailAddressAttribute : RegularExpressionAttribute
{
public EmailAddressAttribute( )
: base( Validation.EmailAddressRegex ) { }
}
しかし、それはクライアントにとっては機能しないようです。ただし、Regularexpression(validation.emailaddressregex)を使用する場合、正常に動作するようです。
解決
クライアント側の検証を有効にするには、新しい属性のアダプターを登録する必要があります。
RegularexpressionAttributeにはすでにアダプターがあり、これはRegularexpressionAttributeAdapterであるため、再利用する必要があります。
静的コンストラクターを使用して、必要なすべてのコードを同じクラス内に保持します。
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class EmailAddressAttribute : RegularExpressionAttribute
{
private const string pattern = @"^\w+([-+.]*[\w-]+)*@(\w+([-.]?\w+)){1,}\.\w{2,4}$";
static EmailAddressAttribute()
{
// necessary to enable client side validation
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAddressAttribute), typeof(RegularExpressionAttributeAdapter));
}
public EmailAddressAttribute() : base(pattern)
{
}
}
詳細については、完全なプロセスを説明するこの投稿をチェックアウトしてください。http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx
他のヒント
CustomValidationAttributeクラスMSDNページ 現在、いくつかの例があります。 Phil Haackedの投稿は時代遅れです。
普遍的な依存プロパティバリデーターを見てください これ 論文
データアノテーションを使用してみましたか?
これは、System.comPonentModel.DataAnnotationsを使用した私のアノテーションプロジェクトです。
public class IsEmailAddressAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
//do some checking on 'value' here
return true;
}
}
これは私のモデルプロジェクトです
namespace Models
{
public class ContactFormViewModel : ValidationAttributes
{
[Required(ErrorMessage = "Please provide a short message")]
public string Message { get; set; }
}
}
これが私のコントローラーです
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ContactUs(ContactFormViewModel formViewModel)
{
if (ModelState.IsValid)
{
RedirectToAction("ContactSuccess");
}
return View(formViewModel);
}
プロジェクトを取得してコンパイルする必要があるため、Data AnnotationsをGoogle Googleで確認する必要があります。私はそれをしますが、私はここで長い端で外に出る必要があります。
お役に立てれば。
編集