简体   繁体   中英

How to validate list of string using EmailAddressAttribute in C#?

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.

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);
    }
}

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM