How to create custom validation attribute for MVC
Asked Answered
P

4

12

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 validation. Can anyone point me in the right direction?

I tried something as simple as this:

[AttributeUsage( AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false )]
public class EmailAddressAttribute : RegularExpressionAttribute
{
    public EmailAddressAttribute( )
        : base( Validation.EmailAddressRegex ) { }
}

but it doesn't seem to work for the client. However, if I use RegularExpression(Validation.EmailAddressRegex)] it seems to work fine.

Piperidine answered 5/3, 2010 at 0:8 Comment(4)
You do inherit from RegularExpressionAttribute in your example?Accidie
I've tried it both ways but can't seem to get it to work.Piperidine
I would suggest you checking Phil Haacks excellent post about validation.Diplomatic
You need to register an adapter for the new attribute in order to enable client side validation. See my example below.Baku
B
38

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

Baku answered 10/5, 2011 at 18:10 Comment(1)
This regex would invalidate the valid email address "[email protected]"Heartsome
R
3

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

Retinitis answered 30/3, 2011 at 18:34 Comment(0)
O
0

Look at the universal Dependent Property Validator in this article

Overrule answered 2/8, 2011 at 14:15 Comment(0)
S
-2

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.

Ster answered 5/3, 2010 at 4:39 Comment(1)
But does that work on client-side? As far as I understand, that's what he is asking.Accidie

© 2022 - 2024 — McMap. All rights reserved.