Allow empty strings for fields marked with PhoneAttribute or UrlAttribute

c# data-annotations ef-code-first entity-framework validation


CodeFirst Entity Framework 5 is what I'm utilizing. I have a class that corresponds to a user.

public class User
    public int UserId { get; set; }

    [Required(AllowEmptyStrings= true)]
    public string WebSite { get; set; }

    [Required(AllowEmptyStrings = true)]
    public string Phone { get; set; }

    [Required(AllowEmptyStrings = true)]
    public string Fax { get; set; }

I appreciate the mechanisms forPhone and Url Sadly, validation fails when fields designated with these attributes are empty strings, even though this is what I want to be allowed.[Required(AllowEmptyStrings = true)] appears to be ineffective withPhone or Url characteristics. The same appears to be true for some more DataAnnotations characteristics, such asEmailAddress .

Is there a method to let fields tagged with these attributes accept empty strings?

10/2/2013 11:07:05 AM

Accepted Answer

validation qualities such as[Phone] and [EmailAddress] will verify any string values that aren't null. Due to thestring given that type is intrinsically nullable and empty strings are read as null by the ModelBindernull This succeeds in the validation test.

After including the[Required] the string effectively ceases to be nullable. EF will script a non-nullable database field if Code First is being used. A blank value will now be interpreted as by the ModelBinder.String.Empty It will not pass the attribute validation test.

Therefore, it is impossible to allow empty strings with validation characteristics, but null strings are permissible. You only need to remove the[Required] attribute. Values that are empty willnull and values that are not empty will be verified.

In my situation, I was having trouble importing entries from a CSV file because I had skipped the standard ModelBinder. Be sure to include a manual check before saving to your data model if you are performing something unique like this:

Email = (record.Email == String.Empty) ? null : record.Email
12/18/2013 8:50:17 PM

Popular Answer

Use the two data annotations listed below:

[Required(AllowEmptyStrings = true)]
[DisplayFormat(ConvertEmptyStringToNull = false)]

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow