c# - DataAnnotations [Phone] 属性

标签 c# regex asp.net-mvc validation data-annotations

[电话] 属性的默认有效格式是什么? 数据表中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 时存在映射问题。更新模型还不够,所以我不得不使用表映射手动更改值。

Error 2019: Member Mapping specified is not valid. The type 'Edm.Int32[Nullable=False,DefaultValue=]' of member 'Phone' in type 'UserDBModel.UserProfile' is not compatible with 'SqlServerCe.nvarchar[Nullable=False,DefaultValue=,MaxLength=16,Unicode=True,FixedLength=False]' of member 'Phone' in type 'UserDBModel.Store.UserProfile'.

最佳答案

现在可以通过使用 .NET Reference Source (.NET Framework 2.7.2) 浏览源代码轻松找到 PhoneAttribute 的默认正则表达式或 source.dot.net (.NET Core)

它显示(丑陋的)正则表达式被定义为:

private static Regex _regex = new Regex(@"^(\+\s?)?((?<!\+.*)\(\+?\d+([\s\-\.]?\d+)?\)|\d+)([\s\-\.]?(\(\d+([\s\-\.]?\d+)?\)|\d+))*(\s?(x|ext\.?)\s?\d+)?$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);

这回答了您的直接问题,但是否有帮助还有待观察。也许这将是创建您自己的修改后的电话号码正则表达式的良好基础。

Sample Regex Matches

关于c# - DataAnnotations [Phone] 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19595135/

相关文章:

c# - 如何将字符串与列表框中的所有项目进行比较?

c# - AutoMapper继承和Linq

python - 如何在 Python 中从列中拆分和提取位置名称

regex - 使用正则表达式修剪尾随空格

asp.net-mvc - 在 ASP.NET MVC Core 中以弹出模式显示搜索结果的最佳实践

c# - 将sql返回保存在一个字符串中

c# - 443 端口的备用端口是什么?

asp.net-mvc - 在 MVC2 中使用 FormsAuthenticationTicket cookie 自定义 IIdentity 和 IPrincipal

java - 使用 Pig Latin(或一般的 java)的 FILTER 正则表达式

c#数据表批处理