Phone Number Validation MVC

后端 未结 9 1314
轮回少年
轮回少年 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:27

    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" })
    
    0 讨论(0)
  • 2020-12-07 21:30

    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>
    
    0 讨论(0)
  • 2020-12-07 21:34

    Try for simple regular expression for Mobile No

    [Required (ErrorMessage="Required")]
    [RegularExpression(@"^(\d{10})$", ErrorMessage = "Wrong mobile")]
    public string Mobile { get; set; }
    
    0 讨论(0)
  • 2020-12-07 21:38

    Try this:

    [DataType(DataType.PhoneNumber, ErrorMessage = "Provided phone number not valid")]
    
    0 讨论(0)
  • 2020-12-07 21:41

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-07 21:41

    The phone number data annotation attribute is for the data type, which is not related to the data display format. It's just a misunderstanding. Phone number means you can accept numbers and symbols used for phone numbers for this locale, but is not checking the format, length, range, or else. For display string format use the javascript to have a more dynamic user interaction, or a plugin for MVC mask, or just use a display format string properly.

    If you are new to MVC programming put this code at the very end of your view file (.cshtml) and see the magic:

    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#the_id_of_your_field_control").keyup(function () {
                $(this).val($(this).val().replace(/^(\d{2})(\d{5})(\d{4})+$/, "($1) $2-$3"));
            });
        });
    </script>
    

    This format is currently used for mobile phones in Brazil. Adapt for your standard.

    This will add the parenthesis and spaces to your field, which will increase the string length of your input data. If you want to save just the numbers you will have to trim out the non-numbers from the string before saving.

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