我想从一个输入字段中过滤电话号码和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>发布于 2021-11-09 08:55:01
根据值来允许多种格式有点棘手。电话号码没有真正的标准(除了国际电话号码的起始号码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>https://stackoverflow.com/questions/69882161
复制相似问题