Wasiu
Wasiu

Reputation: 419

Input validation using typeof

I'm working on input validation, I dont want to use RegExp but I keep wondering why typeof is not working inside if statement or is anything wrong with my code

function myDom(){
    
    var message = document.getElementById('show');
    var xx = document.getElementById('demo').value;
    try{
        if(xx === "") throw "can not be empty";
        if(typeof xx === "number") throw "can not be number";
        //if(xx < 100) throw "less than hundreds!"
   }catch(err){
       message.innerHTML = "input " + err;
   }
    
}

Upvotes: 0

Views: 188

Answers (1)

Mamun
Mamun

Reputation: 68933

The type of input value is always string. Since you are comparing with strictly equality operator (===), you have to convert them to number. You should convert the value only if the value is only number using (isNaN) or not empty:

var elValue = document.getElementById('demo').value;
var xx = isNaN(elValue) || elValue == '' ? elValue: Number(elValue);

Demo:

function myDom(){
  var message = document.getElementById('show');
  var elValue = document.getElementById('demo').value.trim();
  var xx = isNaN(elValue) || elValue == '' ? elValue: Number(elValue);
  try{
    if(xx === "") throw "can not be empty";
    else if(typeof xx === "number") throw "can not be number";
    else message.innerHTML = '';
    //if(xx < 100) throw "less than hundreds!"
  }catch(err){
    message.innerHTML = "input " + err;
  }
}
<input id="demo" oninput="myDom()"/>
<div id="show"></div>

Upvotes: 2

Related Questions