The DataAnnotations [Phone] Attribute

妖精的绣舞 提交于 2019-12-04 16:22:46

问题


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!")]

Related code:

    [Required]
    [Phone]
    public string Phone { get; set; }

    <div class="editor-field">
       @Html.EditorFor(model => model.Phone)
       @Html.ValidationMessageFor(model => model.Phone)
    </div>

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.

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


回答1:


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.




回答2:


Try this -

  [Required(ErrorMessage = "Mobile no. is required")]
  [RegularExpression("^(?!0+$)(\\+\\d{1,3}[- ]?)?(?!0+$)\\d{10,15}$", ErrorMessage = "Please enter valid phone no.")]
  public string Phone { get; set; }


来源:https://stackoverflow.com/questions/19595135/the-dataannotations-phone-attribute

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