The DataAnnotations [Phone] Attribute

前端 未结 2 1176
南方客
南方客 2021-02-07 05:10

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 va

相关标签:
2条回答
  • 2021-02-07 05:19

    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; }
    
    0 讨论(0)
  • 2021-02-07 05:32

    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.

    0 讨论(0)
提交回复
热议问题