3

I have a class say "Request". It has two properties as given below. The email validation for Recipient works fine. However it does not work for Recipients.

[EmailAddress] 
public string Recipient { get; set; }

[EmailAddress] 
public List<string> Recipients { get; set; }

Appreciate any help.

Adarsh Kumar
  • 1,134
  • 7
  • 21

2 Answers2

9

You can use the existing EmailAddress attribute inside a custom attribute.

[AttributeUsage(AttributeTargets.Property)]
public sealed class EmailAddressListAttribute : ValidationAttribute
{
    private const string defaultError = "'{0}' contains an invalid email address.";
    public EmailAddressListAttribute()
        : base(defaultError) //
    {
    }

    public override bool IsValid(object value)
    {
        EmailAddressAttribute emailAttribute = new EmailAddressAttribute();
        IList<string> list = value as IList<string>;
        return (list != null && list.All(email => emailAttribute.IsValid(email)));
    }

    public override string FormatErrorMessage(string name)
    {
        return String.Format(this.ErrorMessageString, name);
    }
}
kalthir
  • 797
  • 7
  • 14
1

I ended up with this:

/// <summary>
/// 
/// </summary>
[DataContract]
public class EmailAddress
{
    /// <summary>
    /// 
    /// </summary>
    [DataMember]
    [EmailAddress]
    public string Id { get; set; }

    /// <summary>
    /// 
    /// </summary>
    [DataMember(Name = "Name")]
    public string DisplayName { get; set; }
}
Adarsh Kumar
  • 1,134
  • 7
  • 21