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?
Use following two data annotations:
[Required(AllowEmptyStrings = true)]
[DisplayFormat(ConvertEmptyStringToNull = false)]