有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?
当前回答
ReactJS:
<input
onKeyPress={(event) => {
if (!/[0-9]/.test(event.key)) {
event.preventDefault();
}
}}
/>
其他回答
下面是我喜欢使用的一个很好的简单的解决方案:
function numeric_only (event, input) {
if ((event.which < 32) || (event.which > 126)) return true;
return jQuery.isNumeric ($(input).val () + String.fromCharCode (event.which));
}// numeric_only;
<input type="text" onkeypress="return numeric_only (event, this);" />
解释:
使用“事件。-首先确定它是否是一个可打印字符。如果不是,那么允许它(如删除和退格)。否则,将字符连接到字符串的末尾,并使用jQuery的“isNumeric”函数测试它。这样就避免了测试每个角色的单调乏味,也适用于剪切/粘贴场景。
如果你想变得更可爱,那么你可以创建一个新的HTML输入类型。让我们称它为“numeric”,这样你就可以有这样的标签:
<input type="numeric" />
它只允许数字字符。只需添加下面的“文档”。准备好”命令:
$(document).ready (function () {
$("input[type=numeric]").keypress (function (event) {
if ((event.which < 32) || (event.which > 126)) return true;
return jQuery.isNumeric ($(this).val () + String.fromCharCode (event.which));
});// numeric.keypress;
});// document.ready;
HTML并不关心你使用的类型名称-如果它不识别它,那么它将默认使用一个文本框,所以你可以这样做。你的编辑可能会抱怨,但这就是问题所在。毫无疑问,清教徒会抓狂,但它很有效,很简单,到目前为止对我来说还很强大。
更新
这里有一个更好的方法:它考虑到文本选择,并使用本地javascript:
verify (event) {
let value = event.target.value;
let new_value = `${value.substring (0, event.target.selectionStart)}${event.key}${value.substring (event.target.selectionEnd)}`;
if ((event.code < 32) || (event.code > 126)) return true;
if (isNaN (parseInt (new_value))) return false;
return true;
}// verify;
使用这个正则表达式/\D*/g
const phoneHandler = (event: React.ChangeEvent<HTMLInputElement>) =>{
setPhone(event.target.value.replaceAll(/\D*/g, ''));};
下面是emkey08的JavaScript Wiki答案的一个面向对象的重新实现,它使用了一个EventListener对象实现。(参见:MDN web docs EventListener)
在某种程度上,它可以防止为每个过滤后的输入元素重复匿名事件处理程序函数声明,同时仍然允许它通过可选的回调。
/** * Base input {@see Element} {@see EventListener} filter abstract class * * @implements EventListener */ class AbstractInputFilter { /** * Attach the input filter to the input {@see Element} * * @param inputElement The input {@see Element} to filter * @param isValid - The callback that determines if the input is valid. * @throws Error */ constructor(inputElement, isValid = null) { // Abstract class if (this.constructor === AbstractInputFilter) { throw new Error("Object of Abstract Class cannot be created"); } if (typeof isValid === "function") { this.isValid = isValid; } for (const event of ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"]) { inputElement.addEventListener(event, this); } } /** * Checks the value is valid * * @callback isValid default call-back that will throw * an {Error} if not implemented by extending this * {AbstractInputFilter} class. * * @param value The value to check * @returns {boolean} * @throws Error */ isValid(value) { throw new Error('must be implemented by callback!'); } /** * Handles the {@see event} dispatched by * the {@see EventTarget} object from the input {@see Element} * to filter its contant while it is being filled. * * @param event the {@see event} dispatched by * the {@see EventTarget} input {@see Element} * @override */ handleEvent(event) { const inputElement = event.currentTarget; if (this.isValid(inputElement.value)) { inputElement.oldValue = inputElement.value; inputElement.oldSelectionStart = inputElement.selectionStart; inputElement.oldSelectionEnd = inputElement.selectionEnd; } else if (inputElement.hasOwnProperty("oldValue")) { inputElement.value = inputElement.oldValue; inputElement.setSelectionRange( inputElement.oldSelectionStart, inputElement.oldSelectionEnd); } else { this.value = ""; } } } /** * Generic Input element {@see EventListener} filter * * @extends AbstractInputFilter * It needs the {@see AbstractInputFilter~isValid} callback * to determine if the input is valid. */ class InputFilter extends AbstractInputFilter {} /** * Unsigned Integer Input element {@see EventListener} filter * @extends AbstractInputFilter */ class UIntInputFilter extends AbstractInputFilter { isValid(value) { return /^\d*$/.test(value); } } /** * Unsigned Float Input element {@see EventListener} filter * @extends AbstractInputFilter */ class UFloatInputFilter extends AbstractInputFilter { isValid(value) { return /^\d*\.?\d*$/.test(value); } } // Filter with pre-made InputFilters (re-use the filter) new UIntInputFilter(document.getElementById("UInt")); new UFloatInputFilter(document.getElementById("UFloat")); // Filter with custom callback filter anonymous function new InputFilter(document.getElementById("AlNum"), function(value) { return /^\w*$/.test(value); }); <label>Unsigned integer: </label><input id="UInt"><br/> <label>Unsigned float: </label><input id="UFloat"><br/> <label>AlphaNumeric (no special characters): </label><input id="AlNum">
ReactJS:
<input
onKeyPress={(event) => {
if (!/[0-9]/.test(event.key)) {
event.preventDefault();
}
}}
/>
对于喜欢说俏皮话的人。
string.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');
我在输入type="text"上使用这段代码,并使用AngularJS在按键时激活,但如果喜欢,可以使用jQuery。只需将此代码放入一个函数中,该函数以某种方式通过按键激活。
它只允许数字,数字+十进制,数字+十进制+数字。
CODE
YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d{0,2})(.*)/, '$1');
testOne = "kjlsgjkl983724658.346.326.326..36.346"
=> "983724658.34";
testTwo = ".....346...3246..364.3.64.2346......"
=> "346.";
testThree = "slfdkjghsf)_(*(&^&*%^&%$%$%^KJHKJHKJKJH3"
=> "3";
testFour = "622632463.23464236326324363"
=> "622632463.23";
这是为美国货币构建的,但它可以更改为允许超过两个小数点后的第一个小数,如下所示…
改变了代码
YourString.replace(/[^\d\.]/g, '').replace(/^\.*/, '').replace(/(\.\d*)(.*)/, '$1');
testFour = "dfskj345346346.36424362jglkjsg....."
=> "345346346.36424362";
:)