首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Javascript中使用输入掩码获取Mac ID和电话号码

问如何在Javascript中使用输入掩码获取Mac ID和电话号码
EN

Stack Overflow用户
提问于 2021-11-08 10:40:34
回答 1查看 97关注 0票数 1

我想从一个输入字段中过滤电话号码和Mac id ...如果字符串以'00‘开头,则在每两个带字符的整数后面加一个冒号&如果它以任何其他数字开头,则不在两个数字后面加一个冒号……

代码语言:javascript
复制
var dynamicMask = new IMask(document.getElementById('user'), {
    mask: [{
      mask: '0*:**:**:**:**:**'
    },
    {
      mask: /^\S*@?\S*$/
    }
  ]
})


<script src="https://unpkg.com/imask"></script>
<div class="form-group">
  <label>Mac id or phone</label>
  <input type="text" class="form-control" name="user" id="user" placeholder="Enter ..." />
</div>
EN

回答 1

Stack Overflow用户

发布于 2021-11-09 08:55:01

根据值来允许多种格式有点棘手。电话号码没有真正的标准(除了国际电话号码的起始号码00或+,国内电话号码的起始号码为0,提供商/地点的起始号码为1-9 ),电话号码的长度也可以是12,而且它们几乎不依赖于目标的国家/提供商/地点。

我建议根据输入长度/值使用两个不同的输入域,而不是两个结构。

但是像这样的东西就可以做到:

代码语言:javascript
复制
<input type="text" id="user">
<script>
  /*
   * This allows:
   
   @0123456789af,  @01:23:45:67:89:af and 01:23:45:67:89:af 
      threaded as mac address
   
   any other input like:
   00:00:00:00:00 or 01:23:45:67:89:az
     handled as phone number
     (removes any non numeric value on focusout)
 */
  IMask(user, {
    mask: /[@:0-9a-f]/gi, // allow anything
    prepare(char) {
      // allow only @, :, 0-9 and a-f for input
      // this allows: @[a-f0-9]{12} values to be entered or 00:00:00:00:00:00...
      return char.replace(/[^@:0-9a-f]/i, '');
    },
    commit(value, masked) {
      // leading @ will be removed
      // check if it contains already a : and has a length of 6 sets with 2 byte length each
      if (value.split(':').length == 6 && value.split(':').every(p => p.length == 2) && !value.startsWith('@')) {
        // add an @ leading for the text below
        value = '@' + value;
      }
      value = value.replace(/:/g, '');
      const dummy = document.createElement("input");
      // required else call for IMask() on dummy won't work
      document.body.appendChild(dummy);
      dummy.setAttribute("value", value.startsWith('@') ? value.substr(1) : value);
      // length must be 12 and should not start with 00
      if (/^@[0-9a-f]{12}$/i.test(value)) {
        // remove the leading @ that was added before or by the user and add : formation
        masked._value = IMask(dummy, {
          mask: '**:**:**:**:**:**'
        })._value;
      } else {
        // filter only numbers
        masked._value = IMask(dummy, {
          mask: /.*/,
          prepare(str) {
            return str.replace(/[^0-9]/, '');
          }
        })._value;
      }
      dummy.remove();
    }
  });
</script>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69882161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档