简体   繁体   中英

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,

  1. It should accept only positive numbers and min value is 0.5
  2. It should accept values like 1.5, 0.5 but not values like 1.5.5, 12.5.6, -0.5

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 .

If the function raises a true flag, the input is invalid .
If you want to invert the logic (like: isValidInput ) than use return !( /*logic here*/ );

Using ES6 syntax :

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

You can prevent user from entering more than 1 . and - using e.preventDefault() in keydown event.

 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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM