允许使用PhoneAttribute或UrlAttribute标记的字段使用空字符串 [英] Allow empty strings for fields marked with PhoneAttribute or UrlAttribute
问题描述
我使用CodeFirst Entitty框架5.我有一个表示用户的类。
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; }
}
我喜欢电话的验证机制
和
Url
属性很多,但不幸的是验证失败,当标记这些属性的字段是我实际想要允许的空字符串。 [必需(AllowEmptyStrings = true)]
似乎不适用于电话
或网址
属性。同样的情况似乎也适用于某些其他DataAnnotations属性,如 EmailAddress
。
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?
推荐答案
验证属性如 [Phone]
和 [EmailAddress]
将检查任何非空字符串值。因为 string
类型本身是可空的,所以传递给ModelBinder的空字符串将被读取为 null
,通过验证检查
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.
当您添加 [必需]
属性时,该字符串将变得有效地不可为空。 (如果使用代码优先,EF将脚本不可空数据库列。)ModelBinder现在将解释一个空值为 String.Empty
- 这将导致属性验证检查失败
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.
所以没有办法允许具有验证属性的空字符串,但您可以允许 null 字符串。所有你需要做的是删除 [必需]
属性。空值将为 null
,非空白值将被验证。
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.
在我的情况下,我正在导入记录从CSV文件,并有这个问题,因为我正在跳过正常的ModelBinder。如果您正在做这种不寻常的事情,请确保在保存到数据模型之前包含手动检查:
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
这篇关于允许使用PhoneAttribute或UrlAttribute标记的字段使用空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!