How to create custom validation attribute for MVC

前端 未结 4 1765
我寻月下人不归
我寻月下人不归 2020-11-27 06:06

I\'d like to create a custom validation attribute for MVC2 for an email address that doesn\'t inherit from RegularExpressionAttribute but that can be used in client validati

相关标签:
4条回答
  • 2020-11-27 06:26

    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

    0 讨论(0)
  • 2020-11-27 06:32

    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.

    0 讨论(0)
  • 2020-11-27 06:35

    Look at the universal Dependent Property Validator in this article

    0 讨论(0)
  • 2020-11-27 06:45

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

    0 讨论(0)
提交回复
热议问题