如何在键入和/或粘贴文本时清除(仅限数字和连字符)和自动格式化(连字符和前导零插入)文本输入值



SO上也有类似的问题,但我的问题有点独特。我想将输入文本字段的长度限制为9个字符(目前使用maxlength属性求解(,只允许键入数值和连字符。有点用这个代码处理,返回";真":

/^d*-?d*$/.test(value)

我遇到的问题是,我希望输入文本字段在用户键入以下格式时自动格式化值:

12345-123

如果它是5位数字(根据用户的输入方式,可能有前导零或没有前导零(,后面跟着一个连字符,那么总是3位数字。如果用户输入类似"0"的内容,我希望它用0填充前5个;123-495";因此它将变成";00123-495";。

我不知道如何添加自动零填充,或自动放置连字符。

不反对使用jQuery,但更喜欢香草。

编辑:我觉得添加可能有用。这是一个门禁卡号输入框。因此,值将始终为正数,并且在单个连字符后始终有3位数字。卡号的长度将始终为5位数,但也可以用零填充以使其达到该长度。理想的输出应该总是"0";xxxxx-xxx";。

编辑2:这似乎有效,但存在一个问题,即用户可以在第一个条目开始和之后输入非数字字符,只有这样才能清除它。它似乎也不让我把退格打过连字符。。。有没有办法防止它完全允许使用字母字符?

// Restricts input for the given textbox to the given inputFilter function.
function setInputFilter(textbox, inputFilter) {
["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
textbox.addEventListener(event, function() {
if (inputFilter(this.value)) {
// Current value
new_val = '';
if (this.value.includes('-') && this.value.slice(this.value.indexOf('-')).length == 4) {
console.log("Value not hyphenated yet");
pad_needed = 5 - this.value.indexOf('-');
console.log('Pad needed: ' + pad_needed);
new_val = this.value.padStart(9, '0');
this.value = new_val;
} else if (this.value.length >= 5 && this.value.includes('-') && this.value.slice(this.value.indexOf('-')).length == 4) {
if (this.value.slice(5, 1) == '-') {
// Already a hyphen added, just add rest of numbers
new_val = this.value.slice(0, 6) + this.value.slice(6);
} else {
// Needs hyphen added
new_val = this.value.slice(0, 5) + '-' + this.value.slice(6);
}
this.value = new_val;
} else if (this.value.length >= 5 && !this.value.includes('-')) {
// Needs hyphen added
new_val = this.value.slice(0, 5) + '-' + this.value.slice(6);
this.value = new_val;
}
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
});
}
setInputFilter(document.getElementById("card-number"), function(value) {
return /^d*-?d*$/.test(value); // Allow digits and '-' only
});

function getSanitizedInputValue(value) {
value = value
.trim()
.replace(/^[-]+/, '')
.replace(/[-]+/, '-');
let [
first,
...rest
] = (value.match(/[-d]+/g) ?? [])
.join('')
.split('-')
let joiner = '';
if (first.length >= 6) {
joiner = '-';
rest.unshift(first.slice(5));
first = first.slice(0, 5);
} else if (rest.length >= 1) {
joiner = '-';
first = first.padStart(5, '0');
}
return [
first,
rest.join(''),
]
.join(joiner)
.slice(0,9);
}
function handleInput({ currentTarget: control }) {
const { value: recentValue, selectionStart, selectionEnd } = control;
const regXHasHyphen = /-/;
const sanitizedValue = getSanitizedInputValue(recentValue);
const sanitizedLength = sanitizedValue.length;
const recentLength = recentValue.length;
const positionDelta = ( 
(recentLength <= 5) &&
(sanitizedLength >= 6) &&
(sanitizedLength - recentLength)
) || (
!regXHasHyphen.test(recentValue) &&
regXHasHyphen.test(sanitizedValue) &&
1
) || 0;
control.value = sanitizedValue;
control.selectionStart =
Math.min(sanitizedLength, (selectionStart + positionDelta));
control.selectionEnd =
Math.min(sanitizedLength, (selectionEnd + positionDelta));
}
document
.querySelector('[type="text"]')
.addEventListener('input', handleInput);
<input type="text" maxlength="9" />

最新更新