I\'m using forms in HTML and javascript. I would like an alert to pop up only if the user inputs a LETTER and clicks submit
.
So I have
You could use the isNaN Function. It returns true if the data is not a number. That would be something like that:
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
if (isNaN(x)) // this is the code I need to change
{
alert("Must input numbers");
return false;
}
}
Note: isNan considers 10.2 as a valid number.
You can use the isNaN function to determine if a value does not convert to a number. Example as below:
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
if (isNaN(x))
{
alert("Must input numbers");
return false;
}
}
function isNumber(data){
data = data +"e1"; // Disallow eng. notation "10e2"+"e1" is NaN
var clean = parseFloat(data,10) / data ; // 1 if parsed cleanly
return ( data==0 || clean && (data/data) === 1.0); // Checks for NaN
}
function isInteger(data){
data = data +"e1"; // Disallow eng. notation "10e2"+"e1" is NaN
var clean = parseInt(data,10) / data ; // 1 if parsed cleanly
return (data==0 ||clean && (data%1) === 0); // Checks For integer and NaN
}
//Expected pass
console.log(isNumber("0"))
console.log(isNumber("-0.0"))
console.log(isNumber("+0.0"))
console.log(isNumber(0))
console.log(isNumber(-0.0))
console.log(isNumber(+0.0))
console.log(isNumber(1))
console.log(isNumber(-10.0))
console.log(isNumber(+1000.000001))
console.log(isNumber(1))
console.log(isNumber(-10.0))
console.log(isNumber(+1000.000001))
//Expected fail
console.log(isNumber("FF"))
console.log(isNumber("1e1"))
console.log(isNumber("seven"))
I think the easiest would be to create a Number
object with the string and check if with the help of isInteger
function provided by Number
class itself.
Number.isInteger(Number('1')) //true
Number.isInteger(Number('1 mango')) //false
Number.isInteger(Number(1)) //true
Number.isInteger(Number(1.9)) //false
Try this:
if(parseInt("0"+x, 10) > 0){/* x is integer */}
A better(error-free) code would be like:
function isReallyNumber(data) {
return typeof data === 'number' && !isNaN(data);
}
This will handle empty strings as well. Another reason, isNaN("12")
equals to false
but "12"
is a string and not a number, so it should result to true
. Lastly, a bonus link which might interest you.