Is the DataTypeAttribute validation working in MVC2?

wenqiang picture wenqiang · Mar 6, 2010 · Viewed 13k times · Source

As far as I know the System.ComponentModel.DataAnnotations.DataTypeAttribute not works in model validation in MVC v1. For example,

public class Model
{
  [DataType("EmailAddress")]
  public string Email {get; set;}
}

In the codes above, the Email property will not be validated in MVC v1. Is it working in MVC v2?

Answer

LukLed picture LukLed · Mar 6, 2010

[DataType("EmailAddress")] doesn't influence validation by default. This is IsValid method of this attribute (from reflector):

public override bool IsValid(object value)
{
    return true;
}

This is example of custom DataTypeAttribute to validate Emails (taken from this site http://davidhayden.com/blog/dave/archive/2009/08/12/CustomDataTypeAttributeValidationCustomDisplay.aspx):

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple  = false)]
public class EmailAddressAttribute : DataTypeAttribute
{
    private readonly Regex regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.Compiled);

    public EmailAddressAttribute() : base(DataType.EmailAddress)
    {

    }

    public override bool IsValid(object value)
    {

        string str = Convert.ToString(value, CultureInfo.CurrentCulture);
        if (string.IsNullOrEmpty(str))
            return true;

        Match match = regex.Match(str);   
        return ((match.Success && (match.Index == 0)) && (match.Length == str.Length));
    }
}