Phone Number Validation MVC

后端 未结 9 1339
轮回少年
轮回少年 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: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 = $"{formatted}";
            return new HtmlString(s);
        }
    }
    

提交回复
热议问题