如何将电话号码屏蔽为123-456-7890?

时间:2020-09-19 22:44:02

标签: javascript html asp.net asp.net-core

在我的数据库中,我的电话号码是123-456-7890和1234567890,在文本框中是否可以使用123-456-7890格式来格式化显示

我认为手机文本框为

 <input asp-for="PhoneNumber" type="tel" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" readonly class="form-control" id="PhoneNumber" placeholder="">

我需要将所有电话号码的格式设置为123-456-7890

我尝试过:

function formatPhoneNumber(txt) {
  if (String(txt)[3] != "-") {
    txt = "" + txt.slice(0, 3) + "-" + txt.slice(3, 6) + "-" + txt.slice(6);
  }
  return txt;
}

并在我的文本框中

<input asp-for="PhoneNumber"  type="tel" readonly pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" onchange="formatPhoneNumber(this)" class="form-control fa-mask" id="PhoneNumber" placeholder="">

2 个答案:

答案 0 :(得分:1)

这里是一个演示,演示如何绑定格式为111-111-1111的Model数据,以及如何更改格式为111-111-1111的输入。 控制器:

public IActionResult Index()
        {
            TestReadOnly t = new TestReadOnly { PhoneNumber = "1231231234" };
            return View(t);
        }

查看:

    @model TestReadOnly
@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>
<input asp-for="PhoneNumber" type="tel" aria-label="Please enter your phone number" placeholder="ex. 111-111-1111" onchange="change()">
@section scripts{ 
    <script type="text/javascript">
        $(function () {
            //bind the data from Model with format 111-111-1111
            let txt = JSON.stringify(@Model.PhoneNumber);
            if (String(txt)[3] != "-") {
                txt = '' + txt.substring(0, 3) + "-" + txt.substring(3, 6) + "-" + txt.substring(6);
            }
            $('[type="tel"]').val(txt); 
        })
    //when change the input value,format 111-111-1111    
    function phoneMask() {
        var num = $(this).val().replace(/\D/g, '');
        $(this).val(num.substring(0, 3) +'-'+  num.substring(3, 6) + '-' + num.substring(6, 10));
    }
    $('[type="tel"]').keyup(phoneMask);
    </script>
}

结果: enter image description here

答案 1 :(得分:0)

如果要调用该函数,可以在<script>formatPhoneNumber("1234567890")</script>标记后编写input

请注意,如果您在(this)中写入input,则参数是元素本身(在这种情况下为input)。

因此,如果您编写(this),只需稍微更改一下功能即可:

function formatPhoneNumber(el)
{
  let txt = el.value; // add this line
  if (String(txt)[3] != "-")
  {
    txt = '' + txt.slice(0, 3) + "-" + txt.slice(3, 6) + "-" + txt.slice(6);
  }
  //return txt // delete this line
  el.value = txt // add this line instead
}

如果您不通过input调用函数(这意味着您写<script>formatPhoneNumber(parameter)</script>),则参数将为document.getElementById("PhoneNumber")

相关问题