[英]Javascript validation for input type number
I have input type number to give the data of number of minutes.我有输入类型号来给出分钟数的数据。 How can I validate this field to accept below scenario,我如何验证此字段以接受以下场景,
I have tried with below code but it is accepting multiple dots,我试过下面的代码,但它接受多个点,
if ( (charCode != 46 && charCode > 31) && (charCode < 48 || charCode > 57)) {
return false;
}
Using a function to test the input value:使用函数测试输入值:
function isInvalidInput (val) { return parseFloat(val) < 0.5 || isNaN(val); } console.log( isInvalidInput("-0.5") ); // true console.log( isInvalidInput(-2) ); // true console.log( isInvalidInput("1.2.5") ); // true console.log( isInvalidInput("0.4") ); // true console.log( isInvalidInput(0.4) ); // true console.log( isInvalidInput("0.5") ); // false console.log( isInvalidInput("1.2") ); // false console.log( isInvalidInput("1000.9") ); // false console.log( isInvalidInput(0.5) ); // false console.log( isInvalidInput(0.999) ); // false
where parseFloat(val) < 0.5
(if necessary parses the string and) makes sure it's greater than 0.5
- disallowing negative values, and isNaN
parses the string and checks if the format is a Number
.其中parseFloat(val) < 0.5
(如有必要,解析字符串并)确保它大于0.5
- 不允许负值,并且isNaN
解析字符串并检查格式是否为Number
。
If the function raises a true
flag, the input is invalid .如果函数引发true
标志,则输入无效。
If you want to invert the logic (like: isValidInput
) than use return !( /*logic here*/ );
如果你想反转逻辑(比如: isValidInput
)而不是使用return !( /*logic here*/ );
Using ES6 syntax :使用ES6 语法:
const isInvalidInput = val => parseFloat(val) < 0.5 || isNaN(val);
You can prevent user from entering more than 1 .
您可以防止用户输入超过 1 .
and -
using e.preventDefault()
in keydown event.和-
在 keydown 事件中使用e.preventDefault()
。
let input = document.querySelector('input'); input.addEventListener('keydown',(e) => { if((e.key === '.' && e.target.value.includes('.')) || e.key === '-'){ e.preventDefault(); console.log("Wrong Input") } }) input.addEventListener('blur',(e) => { if(parseFloat(e.target.value) < 0.5) console.log("Input less than 0.5") })
<input id="main" type="number" min="0.5"/>
You can min
attribute value set to 0.5
, RegExg
/^\\d+$|^\\d+\\.\\d+$/
to match beginning of string one or more digits to end of string, or beginning of string one or more digit characters followed by dot character followed by one or more digit characters followed by end of string and check if .value
is less than min
attribute value at blur
event handler,您可以将min
属性值设置为0.5
, RegExg
/^\\d+$|^\\d+\\.\\d+$/
匹配字符串开头一位或多位数字到字符串结尾,或字符串开头一位或多位数字字符后跟点字符后跟一个或多个数字字符后跟字符串结尾,并在blur
事件处理程序中检查.value
是否小于min
属性值,
<input type="number" min="0.5" onblur="if(!/^\\d+$|^\\d+\\.\\d+$/.test(this.value)||this.value<this.min)this.value=''">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.