0

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

1
  • 1
    What does your current code look like? Commented Aug 25, 2016 at 18:45

3 Answers 3

2

you can use regex to check if its a numeric value

 var reg = new RegExp(/^\d+$/);
 reg.test(yourValue);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

1 Comment

"so essentially there are no types" Oh come on. Somebody already said that and they were wrong then. This is still wrong. If that statement were true, then why does JavaScript have the typeof operator and why does it work? typeof 5 //"number" while typeof "hello" //"string"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.