繁体   English   中英

如何在 Javascript 中为 Mac ID 和电话号码使用输入掩码

[英]How to use input mask in Javascript for Mac ID & Phone Number

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

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>

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

我建议根据输入长度/值使用两个不同的输入字段而不是两个格式。

但是这样的事情会做到:

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM