【问题标题】:Javascript validation for input type number输入类型号的 Javascript 验证
【发布时间】:2019-02-18 06:14:51
【问题描述】:

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

  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;
      }

【问题讨论】:

  • 您实际尝试检测多个点的代码在哪里? “给出分钟数的数据”是什么意思
  • @RokoC.Buljan 这里是检测多个点的代码let df = questionDuration.toString(); let length = df.replace(/[^.]/g, "").length; if(length &gt;1){ return false; }
  • 仍然不确定(因为您提到 分钟)所有有效的输入值是什么...:\
  • @RokoC.Buljan 输入应该接受像 0.5,1 , 2.5 这样的值 输入不应该接受像 0, -1, -2.5 这样的值
  • 9999.9 是否有效?还是59 是最大值?

标签: javascript


【解决方案1】:

使用函数测试输入值:

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) &lt; 0.5(如有必要解析字符串)确保它大于0.5 - 不允许负值,isNaN 解析字符串并检查格式是否为Number

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

使用ES6 syntax

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

【讨论】:

    【解决方案2】:

    您可以在 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") 
    })
    &lt;input id="main" type="number" min="0.5"/&gt;

    【讨论】:

    • @Siva Kumar S 如果您满意,请接受答案。
    【解决方案3】:

    您可以将min 属性值设置为0.5RegExg /^\d+$|^\d+\.\d+$/ 以匹配字符串开头一个或多个数字到字符串结尾,或字符串开头一个或多个数字字符后跟点字符由一个或多个数字字符后跟字符串结尾并检查.value 是否小于min 事件处理程序处的min 属性值,

    <input 
      type="number" 
      min="0.5"  
      onblur="if(!/^\d+$|^\d+\.\d+$/.test(this.value)||this.value<this.min)this.value=''">

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2016-09-23
      • 2017-12-16
      • 1970-01-01
      • 2016-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多