Allow empty strings for fields marked with PhoneAttribute or UrlAttribute

大憨熊 提交于 2019-12-04 09:57:28

问题


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?


回答1:


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



回答2:


Use following two data annotations:

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


来源:https://stackoverflow.com/questions/19135504/allow-empty-strings-for-fields-marked-with-phoneattribute-or-urlattribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!