Ahmed Abbas Ahmed Abbas - 1 year ago 85
HTML Question

Validate if i enter Alphabet

I make a simple program that when i enter any number in text box it add 3 in it.
I want to validate if user enter text then it shows a message "YOU ENTER TEXT".
if i enter any text my if-else is not working
here is my code

<input type="text" id="txt1">
<input type="button" value="EXECUTE" onClick="add()">
<p id="demo1"></p>


function add(){
var num1=document.getElementById("txt1").value;
var a=parseInt(num1);

if(typeof a==='String'){
document.getElementById("demo1").innerHTML="THIS IS STRING";

var ans=(a+3);

Answer Source

To achieve expected result use isNaN() instead of typeof

function add() {
  var num1 = document.getElementById("txt1").value;
  var a = parseInt(num1);

  if (isNaN(a)) {
    document.getElementById("demo1").innerHTML = "THIS IS STRING";
  } else {

    var ans = (a + 3);
    document.getElementById("demo1").innerHTML = ans;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download