Method 1: Use the isNaN() function
This code above creates a form with an input field and a button. When the button is clicked, it calls the checkNumber() function. This function gets the value of the input field and checks if it's a number using the isNaN() function. If the input is not a number, it displays a message saying so. If it is a number, it displays a message saying that it's a number. The message is displayed in a paragraph element with the id "result".
Here is an example of how it looks:
If you enter some obviously non-numeric value, e.g., “sat” it will say that it is not a number:
Method 2: Use a regular expression
This code above, like the earlier example, creates a form with an input field and a button. When the button is clicked, it calls the checkNumber() function. This function gets the value of the input field and checks if it's a number using a regular expression. The regular expression /^-?\d*\.?\d+$/ checks if the input string starts with an optional minus sign (-), followed by zero or more digits (\d*), followed by an optional decimal point (\.?), followed by one or more digits (\d+). If the input matches this pattern, it's considered a number, including floating point numbers. If it doesn't match the pattern, it's not a number. The message is displayed in a paragraph element with the id "result".
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.