简体   繁体   中英

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

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