【发布时间】:2023-04-03 07:54:01
【问题描述】:
[Phone] 属性的默认有效格式是什么? 数据表中phone列是navrchar(16) 如果我输入电话号码,例如 1112223333,我会得到“字段不是有效的电话号码”。 如果我输入 01112223333,我会得到“值 '11112223333' 无效。”
另外,如何覆盖它? 我知道我可以这样做,但在这种情况下这是最佳做法吗?
[RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}",ErrorMessage="Invalid Phone Number!")]
相关代码:
[Required]
[Phone]
public string Phone { get; set; }
<div class="editor-field">
@Html.EditorFor(model => model.Phone)
@Html.ValidationMessageFor(model => model.Phone)
</div>
更新 我猜当我将电话列从 int 更改为 navrchar 时出现了映射问题。更新模型是不够的,所以我不得不使用表映射手动更改值。
错误 2019:指定的成员映射无效。 成员 'Phone' 的类型 'Edm.Int32[Nullable=False,DefaultValue=]' 在“UserDBModel.UserProfile”类型中与 'SqlServerCe.nvarchar[Nullable=False,DefaultValue=,MaxLength=16,Unicode=True,FixedLength=False]' 'UserDBModel.Store.UserProfile' 类型的成员'Phone'。
【问题讨论】:
-
这是一个很好的做法。如果您需要多次使用电话验证,最好创建自己的 ValidationAttribute (PhoneNumberAttribute)。
-
您将数据库中的列更改为“nvarchar”,但将
Phone属性保留在UserDBModel.UserProfile和int中
标签: c# regex asp.net-mvc validation data-annotations