DataAnnotations [Phone]属性 [英] The DataAnnotations [Phone] Attribute

查看:169
本文介绍了DataAnnotations [Phone]属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[Phone]属性的默认有效格式是什么? 在数据表中,电话"列为navrchar(16) 如果输入电话号码,例如1112223333,则会显示字段不是有效的电话号码". 如果输入01112223333,则会收到值'11112223333'无效."

What is the default, valid format of the [Phone] attribute? In the data table, the phone column is navrchar (16) If I enter a phone # like 1112223333, I get "field is not a valid phone number." If I enter 01112223333, I get "The value '11112223333' is invalid."

此外,如何覆盖它? 我知道我可以做这样的事情,但这是这种情况下的最佳做法吗?

Also, how to override it? I understand that I could do something like this, but is this the best practice in this case?

[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时,存在映射问题.更新模型还不够,因此我不得不使用表映射手动更改值.

Update I guess there was a mapping issue when I changed the phone column from int to navrchar. Updating the model was not enough, so I had to change the value manually using the Table Mapping.

错误2019:指定的成员映射无效. 成员电话"的类型"Edm.Int32 [Nullable = False,DefaultValue =]" 类型'UserDBModel.UserProfile'中的内容与 'SqlServerCe.nvarchar [Nullable = False,DefaultValue =,MaxLength = 16,Unicode = True,FixedLength = False]' 'UserDBModel.Store.UserProfile'类型的'Phone'成员.

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'.

推荐答案

现在可以通过使用 source.dot.net ( .NET Core )

The default regular expression for the PhoneAttribute can now be handily found by browsing the source code with .NET Reference Source (.NET Framework 2.7.2) or source.dot.net (.NET Core)

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

There it shows the (ugly) Regex as being defined as:

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);

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

That answers your direct question, but whether it helps or not remains to be seen. Maybe it would be a good base to create your own modified phone number regex.

这篇关于DataAnnotations [Phone]属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆