Allow empty strings for fields marked with PhoneAttribute or UrlAttribute

有些话、适合烂在心里 提交于 2019-12-03 04:27:08

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
user5791468

Use following two data annotations:

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