首页 > 解决方案 > 如何在html5的TextBox中自动在4位数字后插入连字符“-”?

问题描述

我已经在 html5 的输入字段中进行了验证,以获得这种格式 03xx-xxxxxxx。

pattern="03\d{2}-\d{7}"

现在我想在第四位之后自动添加这个连字符。怎么做?

标签: htmlregexformsvalidationautofill

解决方案


我必须建议您不要进行这种类型的输入编辑,因为当您需要编辑错别字时通常会令人沮丧。

我也不知道与可访问性相关的问题。

输入模式只检查提交的数据,所以它不是你要找的。

也就是说,这是 JS 中一种可能的解决方案:

// select the input element
var i = document.querySelector('input.hyphen');
// number of charatcers before the hyphen
var n = 4;
// run this function everytime the user release a key
i.addEventListener('keyup', function (event) { 
  // text cleared of all dashes
  var t = i.value.replace(/-/g, '');
  // save the carret position
  var s = i.selectionStart;
  // beguining string with n digits
  var b = t.substr(0, n);
  // end string with what's left (maxLength)
  var e = t.substr(n);
  // if there are more then n digits
  if (e.length) {
    // join then with a dash
    i.value = [b, e].join('-');
    // if the caret was before the dash put it back to the saved position
    if (s <= n) i.setSelectionRange(s, s);
    // if the caret was next to the dash put it after
    if (s == n+1) i.setSelectionRange(s+1, s+1);
  // if there's no end string then no need for dashes, just show the beguining
  } else i.value = b;
});
<input class="hyphen" placeholder="0000-0000000" maxlength="12">


推荐阅读