'Allow empty string for EmailAddressAttribute

I have property in my PersonDTO class:

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

It works fine, except I want to allow empty strings as values for my model, if I send JSON from client side:

{ Email: "" }

I got 400 bad request response and

{"$id":"1","Message":"The Email field is not a valid e-mail address."}

However, it allows omitting email value:

{ FirstName: "First", LastName: 'Last' }

I also tried:

[DataType(DataType.EmailAddress, ErrorMessage = "Email address is not valid")]

but it does not work.

As far as I understood, Data Annotations Extensions pack does not allow empty string either.

Thus, I wonder if there is a way to customize the standard EmailAddressAttribute to allow empty strings so I do not have to write custom validation attribute.



Solution 1:[1]

It's Easy. Do This. Bye

private string _Email;
[EmailAddress(ErrorMessage = "Ingrese un formato de email vĂ¡lido")]
public string Email { get { return _Email; } set { _Email = string.IsNullOrWhiteSpace(value) ? null : value; } }

Solution 2:[2]

Set TargetNullValue property of the binding to an empty string.

TargetNullValue=''

Solution 3:[3]

I used the suggestion from Yishai Galatzer to make a new ValidationAttribute called EmailAddressThatAllowsBlanks:

namespace System.ComponentModel.DataAnnotations
{
    public class EmailAddressThatAllowsBlanks : ValidationAttribute
    {
        public const string DefaultErrorMessage = "{0} must be a valid email address";
        private EmailAddressAttribute _validator = new EmailAddressAttribute();

        public EmailAddressThatAllowsBlanks() : base(DefaultErrorMessage)
        {

        }

        public override bool IsValid(object value)
        {
            if (string.IsNullOrEmpty(value.ToString()))
                return true;

            return _validator.IsValid(value.ToString());
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Esteban Kito
Solution 2 Jeremy Caney
Solution 3 StevieTimes