Allow empty strings for fields marked with PhoneAttribute or UrlAttribute
Use following two data annotations:
[Required(AllowEmptyStrings = true)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
Validation attributes like [Phone]
and [EmailAddress]
will check any non-null string values. Because the string
type is inherently nullable, empty strings passed to the ModelBinder are read as null
, which passes the validation check.
When you add the [Required]
attribute, the string becomes effectively non-nullable. (If using Code First, EF will script a non-nullable database column.) The ModelBinder will now interpret a blank value as String.Empty
- which will fail the attribute validation check.
So there is no way to allow empty strings with validation attributes, but you can allow null strings. All you need to do is remove the [Required]
attribute. Blank values will be null
and non-blank values will be validated.
In my case, I am importing records from a CSV file, and had this problem because I was skipping the normal ModelBinder. If you are doing something unusual like this, be sure to include a manual check before saving to your data model:
Email = (record.Email == String.Empty) ? null : record.Email