如何在C#中使用EmailAddressAttribute验证字符串列表?

时间:2015-07-28 12:02:17

标签: c# validation data-annotations email-address

我有一个班级说“请求”。它有两个属性,如下所示。收件人的电子邮件验证工作正常。但是它对收件人不起作用。

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

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

感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

您可以在自定义属性中使用现有的EmailAddress属性。

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

答案 1 :(得分:0)

我最终得到了这个:

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