Allow blank line for EmailAddressAttribute

I have a property in my PersonDTO class:

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

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

 { Email: "" } 

I received 400 bad request responses to 400 bad request and

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

However, this allows you to omit the email value:

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

I also tried:

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

But that does not work.

As I understand it, the Data Annotations Extensions package also does not allow an empty string.

So I'm wondering if there is a way to set up a standard EmailAddressAttribute to allow blank lines so that I don't have to write my own validation attribute.

+13
validation asp.net-mvc attributes
source share
2 answers

You have two options:

  • Convert string.Empty to null in the E-mail field. Many times this is perfectly acceptable. You can do this work globally or just make your setter convert string.Empty to null in an email field.
  • Write your own EmailAddress attribute, since the EmailAddressAttribute attribute is sealed, you can wrap it and write your own IsValid forwarding method.

Example:

 bool IsValid(object value) { if (value == string.Empty) { return true; } else { return _wrappedAttribute.IsValid(value); } } 

Extension by option 1 (from Web Api does not convert json empty string values ​​to null )

Add this converter:

 public class EmptyToNullConverter : JsonConverter { private JsonSerializer _stringSerializer = new JsonSerializer(); public override bool CanConvert(Type objectType) { return objectType == typeof(string); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { string value = _stringSerializer.Deserialize<string>(reader); if (string.IsNullOrEmpty(value)) { value = null; } return value; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { _stringSerializer.Serialize(writer, value); } } 

and use the property:

 [JsonConverter(typeof(EmptyToNullConverter))] public string EmailAddress {get; set; } 

or globally in WebApiConfig.cs:

 config.Formatters.JsonFormatter.SerializerSettings.Converters.Add( new EmptyToNullConverter()); 
+26
source share

It is easy. Do it. goodbye

 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; } } 
0
source share

All Articles