Allow empty strings for fields marked with PhoneAttribute or UrlAttribute

Nu-hin picture Nu-hin · Oct 2, 2013 · Viewed 27.9k times · Source

I'm using CodeFirst Entitty framework 5. I have a class representing a user.

public class User
{
    [Key]
    public int UserId { get; set; }

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

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

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

I like the validation mechanics for Phone and Url attributes a lot, but unfortunately validation fails when fields marked with these attributes are empty strings which I actually want to allow. [Required(AllowEmptyStrings = true)] doesn't seem to work with Phone or Url attributes. The same seems to apply to some other DataAnnotations attributes like EmailAddress.

Is there a way to allow empty strings for fields marked with such attributes?

Answer

user5791468 picture user5791468 · Jan 14, 2016

Use following two data annotations:

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