Phone Number Validation MVC

此生再无相见时 提交于 2019-11-27 05:22:08

问题


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:

<ol class="row">
    <li class="cell" style="width: 20%;">Phone Number:</li>
    <li class="cell last" style="width: 60%;">
        @Html.TextBoxFor(model => model.PhoneNumber, new { @class = "textbox" }) 
        @Html.ValidationMessageFor(model => model.PhoneNumber)
    </li>
</ol>

C# Code:

[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone Number")]
[Required(ErrorMessage = "Phone Number Required!")]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
                   ErrorMessage = "Entered phone format is not valid.")]
public string PhoneNumber { get; set; }

However, the input box will not show a message to the user indicating that the phone number which was submitted is not valid.


回答1:


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)



回答2:


Try for simple regular expression for Mobile No

[Required (ErrorMessage="Required")]
[RegularExpression(@"^(\d{10})$", ErrorMessage = "Wrong mobile")]
public string Mobile { get; set; }



回答3:


You don't have a validator on the page. Add something like this to show the validation message.

@Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })



回答4:


To display a phone number with (###) ###-#### format, you can create a new HtmlHelper.

Usage

@Html.DisplayForPhone(item.Phone)

HtmlHelper Extension

public static class HtmlHelperExtensions
{
    public static HtmlString DisplayForPhone(this HtmlHelper helper, string phone)
    {
        if (phone == null)
        {
            return new HtmlString(string.Empty);
        }
        string formatted = phone;
        if (phone.Length == 10)
        {
            formatted = $"({phone.Substring(0,3)}) {phone.Substring(3,3)}-{phone.Substring(6,4)}";
        }
        else if (phone.Length == 7)
        {
            formatted = $"{phone.Substring(0,3)}-{phone.Substring(3,4)}";
        }
        string s = $"<a href='tel:{phone}'>{formatted}</a>";
        return new HtmlString(s);
    }
}



回答5:


Along with the above answers Try this for min and max length:

In Model

[StringLength(13, MinimumLength=10)]
public string MobileNo { get; set; }

In view

 <div class="col-md-8">
           @Html.TextBoxFor(m => m.MobileNo, new { @class = "form-control" , type="phone"})
           @Html.ValidationMessageFor(m => m.MobileNo,"Invalid Number")
           @Html.CheckBoxFor(m => m.IsAgreeTerms, new {@checked="checked",style="display:none" })
  </div>



回答6:


Try this:

[DataType(DataType.PhoneNumber, ErrorMessage = "Provided phone number not valid")]



回答7:


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.




回答8:


[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



来源:https://stackoverflow.com/questions/28904826/phone-number-validation-mvc

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