How to create custom validation attribute for MVC

前端 未结 4 1781
我寻月下人不归
我寻月下人不归 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: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.

提交回复
热议问题