How to create custom validation attribute for MVC

≯℡__Kan透↙ 提交于 2019-11-26 18:54:12
JCallico

You need to register an adapter for the new attribute in order to enable client side validation.

Since the RegularExpressionAttribute already has an adapter, which is RegularExpressionAttributeAdapter, all you have to do is reuse it.

Use a static constructor to keep all the necessary code within the same class.

[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)
    {
    }
}

For more information checkout this post explaining the complete process. http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

Chris S

The CustomValidationAttribute Class MSDN page has a few examples on it now. The Phil Haacked post is out of date.

Look at the universal Dependent Property Validator in this article

Have you tried using Data Annotations?

This is my Annotations project using System.ComponentModel.DataAnnotations;

public class IsEmailAddressAttribute : ValidationAttribute
{
  public override bool IsValid(object value)
  {
    //do some checking on 'value' here
    return true;
  }
}

This is in my Models project

namespace Models
{
    public class ContactFormViewModel : ValidationAttributes
    {
        [Required(ErrorMessage = "Please provide a short message")]
        public string Message { get; set; }
    }
}

This is my controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ContactUs(ContactFormViewModel formViewModel)
{
  if (ModelState.IsValid)
  {
    RedirectToAction("ContactSuccess");
  }

  return View(formViewModel);
}

You'll need to google DataAnnotations as you need to grab the project and compile it. I'd do it but I need to get outta here for a long w/end.

Hope this helps.

EDIT

Found this as a quick google.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!