gpt4 book ai didi

输入类型编号的 Javascript 验证

转载 作者:行者123 更新时间:2023-11-30 19:48:16 25 4
gpt4 key购买 nike

我输入了类型数字来给出分钟数的数据。我如何验证此字段以接受以下情况,

  1. 它应该只接受正数,最小值为 0.5
  2. 它应该接受像 1.5、0.5 这样的值,但不能接受像 1.5.5、12.5.6、-0.5 这样的值

我试过下面的代码,但它接受多个点,

if ( (charCode != 46 && charCode > 31) && (charCode < 48 || charCode > 57)) {
return false;
}

最佳答案

使用函数测试输入值:

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

哪里parseFloat(val) < 0.5 (如有必要,解析字符串并)确保它大于 0.5 - 不允许负值,以及 isNaN解析字符串并检查格式是否为 Number .

如果函数引发一个 true标志,输入无效
如果你想反转逻辑(如: isValidInput )而不是使用 return !( /*logic here*/ );

使用 ES6 syntax :

const isInvalidInput = val => parseFloat(val) < 0.5 || isNaN(val);

关于输入类型编号的 Javascript 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54741391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com