[英]Form validation datatype error in javascript
I get Login Done in all the cases and also this treats the value as the string instead of the number .... 在所有情况下,我都完成“登录完成” ,这也将值视为字符串而不是数字..
function valid() {
let value = document.getElementById('box').value;
alert(typeof value)
if (isNaN(value) || value < 1 || value > 20) {
alert("Login Done")
} else if (name = '') {
alert("try agin")
}
}
Negate the isNaN(value)
check. 否定
isNaN(value)
检查。 Also convert it to a number before the comparison to reduce the confusion 还要在比较之前将其转换为数字,以减少混乱
function valid() { let value = document.getElementById('box').value; let parsedValue = isNaN(value) ? 1 : parseInt(value, 10); console.log(typeof value); console.log(typeof parsedValue); if (parsedValue < 1 || parsedValue > 20) { console.log("Login Done") } else { console.log("try agin") } } valid(); document.getElementById('box').addEventListener('keyup', valid);
<input id="box" value="21" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.