我有一個 HTML 輸入,這個輸入只接受數字字串,
例子:
輸入值: 0123.534534或 -234234.543345 或-13453,這些輸入值有效。字符 或 - 只存在于字串值的第一個位置
我希望輸入值的每個輸入字符都應保留當前有效字串并將無效輸入字符替換為空字符
例子:
當我輸入: 123.g==> 值應立即替換 123。或者當我輸入: g ==> 該值應立即替換為空值。
我找到了一個實作,但它缺少 ( /-/.) 字符
const getDigitsOnly = (value) => String(value).replace(NOT_NUMBERS, '');
uj5u.com熱心網友回復:
從上面的評論...
“為什么 OP 不通過數字型別輸入欄位來限制用戶輸入,例如 ...
<input type="number"/>?”
“任何
type="text"基于自定義驗證的方法,如果做得好,都有變得更加復雜的趨勢,因為從 UX 的角度來看,即時的值清理(在輸入或粘貼時)還必須注意重新建立用戶最近的插入符號位置。 ”
證明上述復雜性......
function stripNeedlessDataFromBoundFieldValue() {
this.value = this.value.replace((/[- .]$/), '');
}
function getSanitizedValue(value) {
value = value
// remove any leading and trailng whitespace (sequences).
.trim()
// remove any character not equal to minus, plus, dot and digit.
.replace((/[^- .\d] /g), '');
if (value.length >= 1) {
let partials = value.split(/(^[ -]?)/);
if (partials.length === 1) {
partials.unshift('');
} else {
partials = partials.slice(1);
}
let [ first, last ] = partials;
last = last.replace((/[ -] /g), '');
// console.log([ first, last ]);
partials = last.split('.');
if (partials.length === 1) {
partials.unshift('');
} else {
partials = [
partials.shift(),
['.', partials.join('')].join(''),
];
}
first = [first, partials[0]].join('');
last = partials[1];
value = [first, last]
.join('')
.replace(
// trim any sequence of leading zeros into a single one.
(/(^[ -]?)0 /),
(match, sign) => [(sign || ''), 0].join('')
)
.replace(
// always ensure a single zero before a leading sole decimal point.
(/(^[ -]?)\. /),
(match, sign) => [(sign || ''), '0.'].join('')
);
}
return value;
}
function sanitizeInputValue(evt) {
const elmNode = evt.currentTarget;
const currentValue = elmNode.value;
const sanitizedValue = getSanitizedValue(currentValue);
if (currentValue !== sanitizedValue) {
const diff = sanitizedValue.length - currentValue.length;
const { selectionStart, selectionEnd } = elmNode;
elmNode.value = sanitizedValue;
elmNode.selectionStart =
(selectionStart diff > 0) ? selectionStart diff : selectionStart;
elmNode.selectionEnd =
(selectionEnd diff > 0) ? selectionEnd diff : selectionEnd;
}
}
function main() {
const textInput = document.querySelector('[type="text"]');
const finalizeBoundFieldValueDebounced = _.debounce(
stripNeedlessDataFromBoundFieldValue.bind(textInput), 1200
);
textInput.addEventListener('input', evt => {
sanitizeInputValue(evt);
finalizeBoundFieldValueDebounced();
});
// // whithout delayed trimming of trailing dot.
//
// document
// .querySelector('[type="text"]')
// .addEventListener('input', sanitizeInputValue);
}
main();
<script src="https://cdn.jsdelivr.net/npm/[email protected]/underscore-umd-min.js"></script>
<input type="text" placeholder="... number only ..."/>
...并將其直接與數字型別欄位進行比較...
<input type="number" placeholder="native number type"/>
......以及Micahel Hamami的方法,特此付諸實施......
function sanitizeInputValue({ currentTarget }) {
currentTarget.value = currentTarget.value.replace(/[^0-9, ,-,.] /g, "");
}
function main() {
document
.querySelector('[type="text"]')
.addEventListener('input', sanitizeInputValue);
}
main();
<input type="text" placeholder="... number only ..."/>
uj5u.com熱心網友回復:
這是我的解決方案。
我們input向輸入框添加一個事件偵聽器,并為每個輸入格式化整個輸入值。
注意:如果提交值時存在,請不要忘記修剪尾隨小數點(例如"123."to "123")。
const inputBox = document.getElementById("inputBox");
inputBox.addEventListener("input", () => {
inputBox.value = format(inputBox.value);
});
function format(str) {
if (!str.length) return str;
str = str.replace(/[^. -\d]/g, "");
const firstChar = str.charAt(0);
str = str.slice(1).replace(/[ -]/g, "");
// Bug fix. Credit goes to @Peter Seliger
// For pointing out the bug
const charArray = [];
let hasDecimalPoint = false;
if (firstChar === ".") {
if (!str.includes(".")) {
hasDecimalPoint = true;
charArray.push("0.");
}
} else charArray.push(firstChar);
// End bug fix
for (let i = 0; i < str.length; i ) {
const char = str.charAt(i);
if (char === ".") {
if (hasDecimalPoint) continue;
if (!i && firstChar !== "0") charArray.push("0");
hasDecimalPoint = true;
}
charArray.push(char);
}
return charArray.join("");
}
<p>Enter your number here</p>
<input id="inputBox" type="text" />
格式函式的演算法。
1:如果輸入為空則回傳輸入 2:洗掉除“-”、“ ”、“.”以外的所有字符 和數字 3:將第一個字符存入變數 4:洗掉第一個字符后的所有“ ”和“-”(如果存在) 5:如果第一個字符是“.” 然后將其替換為“0”。 6.最后洗掉任何重復的小數點(“.”)(如果存在)
這里有一些虛擬資料來測驗格式功能
const dummyData = [
"",
" ",
"-",
".",
".123",
" .123",
"123.3.23",
"12sfdlj3lfs.s d_f",
"12-- .123",
];
uj5u.com熱心網友回復:
這會做你想做的
let someString = " 123.g";
let result = someString.replace(/[^0-9, ,-,.] /g, "");
console.log(result);
有關如何使用正則運算式的更多資訊,請在此處查看 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312742.html
標籤:javascript 正则表达式 验证 消毒 html-输入
