views:

1198

answers:

2

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.

A: 

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.

griegs
But does that work on client-side? As far as I understand, that's what he is asking.
çağdaş
+3  A: 

I would suggest you checking Phil Haacks excellent post about validation.

Darin Dimitrov
The post contains all necessary info to create custom validator (works on both server side and client side), thanks.
Wen Q.