对于标有PhoneAttribute或UrlAttribute的字段,请允许空字符串

Nu-*_*hin 26 c# validation entity-framework data-annotations ef-code-first

我正在使用CodeFirst Entitty框架5.我有一个代表用户的类.

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; }
}
Run Code Online (Sandbox Code Playgroud)

我喜欢验证机制PhoneUrl属性很多,但不幸的是,当标记有这些属性的字段是我想要允许的空字符串时,验证失败.[Required(AllowEmptyStrings = true)]似乎不适用PhoneUrl属性.这似乎适用于其他一些DataAnnotations属性EmailAddress.

有没有办法为标记有这些属性的字段允许空字符串?

小智 37

使用以下两个数据注释:

[Required(AllowEmptyStrings = true)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
Run Code Online (Sandbox Code Playgroud)


Nei*_*ett 22

验证属性[Phone]和,[EmailAddress]将检查任何非空字符串值.因为string类型本身是可空的,所以传递给ModelBinder的空字符串被读取null,它通过了验证检查.

添加 [Required]属性时,字符串实际上变为不可为空.(如果使用Code First,EF将编写一个不可为空的数据库列.)ModelBinder现在将空值解释为String.Empty- 这将使属性验证检查失败.

因此,无法允许具有验证属性的字符串,但您可以允许字符串.您需要做的就是删除[Required]属性.空白值将null被验证,并且将验证非空白值.

在我的情况下,我从CSV文件导入记录,并有这个问题,因为我正在跳过正常的ModelBinder.如果您正在执行此类异常操作,请务必在保存到数据模型之前包含手动检查:

Email = (record.Email == String.Empty) ? null : record.Email
Run Code Online (Sandbox Code Playgroud)

  • 这似乎不再适用于“System.ComponentModel.DataAnnotations.EmailAddressAttribute”,因为空字符串验证失败,即使该字段不是必需的 (2认同)