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.
```
[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.