Validating a data input javascript

69 Views Asked by At

I have been looking to validate the data input to check whether it is a integer or a string. I looked around and saw some suggestions and typeof suggestions but nothing seems to work.

var nam = prompt("Enter name:")
     person.push(nam);
 var mk1 = prompt("Enter mark 1:");
    var mk1 = parseInt(mk1);
    mark1.push(mk1);
6

There are 6 best solutions below

0
On BEST ANSWER

If you want to check whether input string is not a number try this:

if (isNaN(parseInt(name, 10)) {
    //name is String
} else {
    //name is Number
}
0
On

Use this function: isNaN(parseInt(mk1))

It will return "true" if not a number, and "false" if a number

0
On

use the === operator as below

if (mk1  === parseInt(mk1 , 10))
    alert("mk1 is integer")
else
    alert("mk1 is not an integer. May be String")

If you don't know that the argument is a number-

function isInt(n){
    return Number(n)===n && n%1===0;
}
0
On

Try this way to find input type;

if(!isNaN(parseInt(mk1))) 
  // for integer
else if(!isNaN(parseFloat(mk1)))
 //for float
else
 // String
0
On

When you prompt() the user for data, you always get a string. If you want to check, whether it actually contains just a number, you can try this:

var value = prompt('...'),
    num = parseInt(value, 10);
if (num == value) {
    // ... it is an integer, use `num`
} else {
    // ... it's not an integer (or not *just* an integer), use `value`
}

(or use parseFloat(value) for real numbers).

0
On

It's hard to say what are you trying to do really. You seem to declare var mk1 twice, which looks a bit strange. Also, even if parseInt fails (then returns NaN [Not a Number]) you add it to mark1, which is probably not what you want. Have a look at this:

var nam = prompt("Enter name:")
person.push(nam);

var mk1 = prompt("Enter mark 1:");
mk1 = parseInt(mk1);
if (Number.isNaN(mk1) === false) {
   mark1.push(mk1);
} else {
    alert("mark 1 is not a number");
}