Quantcast
Channel: ASPNETWebStack Issue Tracker Rss Feed
Viewing all articles
Browse latest Browse all 7215

Commented Unassigned: EmailAddressAttribute does not allow empty strings [1112]

$
0
0
I have an MVC4 application and I've decorated a string property with the EmailAddress attribute, but not the Required attribute:

```
[EmailAddress]
string EmailAddress { get; set; }

```

My View uses TextBoxFor to expose the property for editing:

```
@Html.LabelFor(model => model.EmailAddress)
@Html.TextBoxFor(model => model.EmailAddress)
@Html.ValidationMessageFor(model => model.EmailAddress)
```

When I submit the form for processing with an empty string (i.e., left the field in the view blank), it returns to the view, indicating the email address is not valid in the validation message.

Looking at the source code here, the problem seems obvious:

```
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}

string valueAsString = value as string;
return valueAsString != null && _regex.Match(valueAsString).Length > 0;
}
```

I'd love it if that last line was:
```
return !string.IsNullOrEmpty(valueAsString) && _regex.Match(valueAsString).Length > 0;
```

I understand that the empty string is, technically, not a valid email address, but then either is null, and you've taken the time to check for that (twice!). IMHO, it seems more suitable to rely on the Required attribute for checking that a property "has value", and use the other attributes to validate the value meets another requirement.
Comments: When fixing, we need to add an parameter to EmailAddressAttribute for allowing empty email. By default we should keep the old behavior to avoid breaking changes

Viewing all articles
Browse latest Browse all 7215

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>