I setup an if statement that checks for numbers, strings, and null. However when I type "1a" it passes my validation. How does javascript handle this? What type of datatype is this?
How can I say ONLY numbers no strings at all
I setup an if statement that checks for numbers, strings, and null. However when I type "1a" it passes my validation. How does javascript handle this? What type of datatype is this?
How can I say ONLY numbers no strings at all
A simple solution would be to let the browser handle your validation by using the input type number:
<input type="number">
To validate it in JavaScript, you can use the Number() constructor and check for NaN. Note however that it does not only accept digits:
console.log(Number('1a')) // NaN
console.log(Number('1')) // 1
console.log(Number('1.2')) // 1.2
console.log(Number('1e2')) // 100
parseInt()/parseFloat() will not solve your problem, since it ignores trailing non-digits:
console.log(parseInt('a1')) // NaN
console.log(parseInt('1a')) // 1
console.log(parseInt('1')) // 1
console.log(parseFloat('a1')) // NaN
console.log(parseFloat('1a')) // 1
I assume you mean you input 1a into an input box and receive it in a JS function to check what the user has input? If so anything that comes into your function will be a string. If that is the case, you can:
1- Check for the input by doing Number("1a"), which would return NaN if it is not a number or Number("1") would return 1.
2- Use input type=number.
3- Use an input mask library to prevent user from inputing letters and only numbers. In that case you wouldn't need to check on the JS side. Something like this might be what you want: https://github.com/RobinHerbots/jquery.inputmask
As a note it is important to say that JS is not a typed language, so essentially there are no types.
typeof operator and why does it work? typeof 5 //"number" while typeof "hello" //"string"