Siva Kumar S
Siva Kumar S

Reputation: 419

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

Upvotes: 1

Views: 2358

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206593

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 atrue 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);

Upvotes: 1

guest271314
guest271314

Reputation: 1

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=''">

Upvotes: 0

Maheer Ali
Maheer Ali

Reputation: 36594

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"/>

Upvotes: 0

Related Questions