Validating Numbers in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore a JavaScript function that checks whether a given value is a number. We will use the parseFloat() method to convert the value to a number and then validate it using Number.isNaN() and Number.isFinite(). We will also use coercion to check if the value is a number. By the end of this lab, you will have a better understanding of how to validate numbers in JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28688{{"`Validating Numbers in JavaScript`"}} javascript/data_types -.-> lab-28688{{"`Validating Numbers in JavaScript`"}} javascript/arith_ops -.-> lab-28688{{"`Validating Numbers in JavaScript`"}} javascript/comp_ops -.-> lab-28688{{"`Validating Numbers in JavaScript`"}} end

Number Validation Function

To validate if a given input is a number, follow these steps:

  • Open the Terminal/SSH and type node to start practicing coding.
  • Use parseFloat() to try to convert the input to a number.
  • Use Number.isNaN() and logical not (!) operator to check if the input is a number.
  • Use Number.isFinite() to check if the input is finite.
  • Use Number and the loose equality operator (==) to check if the coercion holds.

Here's the code for the validateNumber function:

const validateNumber = (input) => {
  const num = parseFloat(input);
  return !Number.isNaN(num) && Number.isFinite(num) && Number(input) == input;
};

You can use the validateNumber function as follows:

validateNumber("10"); // true
validateNumber("a"); // false

Summary

Congratulations! You have completed the Validate Number lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like