Phone Number Validation MVC

后端 未结 9 1315
轮回少年
轮回少年 2020-12-07 20:51

I am trying to use a regular expression to validate a phone number and return an error when an invalid number or phone number is submitted.

MVC Code

相关标签:
9条回答
  • 2020-12-07 21:48

    [DataType(DataType.PhoneNumber)] does not come with any validation logic out of the box.

    According to the docs:

    When you apply the DataTypeAttribute attribute to a data field you must do the following:

    • Issue validation errors as appropriate.

    The [Phone] Attribute inherits from [DataType] and was introduced in .NET Framework 4.5+ and is in .NET Core which does provide it's own flavor of validation logic. So you can use like this:

    [Phone()]
    public string PhoneNumber { get; set; }
    

    However, the out-of-the-box validation for Phone numbers is pretty permissive, so you might find yourself wanting to inherit from DataType and implement your own IsValid method or, as others have suggested here, use a regular expression & RegexValidator to constrain input.

    Note: Use caution with Regex against unconstrained input per the best practices as .NET has made the pivot away from regular expressions in their own internal validation logic for phone numbers

    0 讨论(0)
  • 2020-12-07 21:51

    Or you can use JQuery - just add your input field to the class "phone" and put this in your script section:

    $(".phone").keyup(function () {
            $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));
    

    There is no error message but you can see that the phone number is not correctly formatted until you have entered all ten digits.

    0 讨论(0)
  • 2020-12-07 21:52

    Model

    [Required(ErrorMessage = "You must provide a phone number")]
    [Display(Name = "Home Phone")]
    [DataType(DataType.PhoneNumber)]
    [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
    public string PhoneNumber { get; set; }
    

    View:

    @Html.LabelFor(model => model.PhoneNumber)
    @Html.EditorFor(model => model.PhoneNumber)
    @Html.ValidationMessageFor(model => model.PhoneNumber)
    
    0 讨论(0)
提交回复
热议问题