Validate Decimal Numbers using the match() method

The match() method is a built-in JavaScript method that allows you to match a string against a regular expression.

Example: Below is the example using the match() method.

Javascript




function validateDecimalNumberUsingMatch(input) {
    // Use the match() method with a regular expression
    const isDecimal = input.match(/^-?\d*\.?\d+$/);
 
    // Return true if it's a valid decimal number, otherwise return false
    return isDecimal !== null;
}
 
// Example usage:
const userInput = "3.14";
if (validateDecimalNumberUsingMatch(userInput)) {
    console.log("Approach 1: Valid decimal number!");
} else {
    console.log("Approach 1: Not a valid decimal number.");
}


Output

Approach 1: Valid decimal number!

How to Validate Decimal Numbers in JavaScript ?

Validating user input is an essential aspect of Web Development. As a developer, when we are playing with the numeric inputs provided by the end-user, it is quite important to ensure that the input provided by the user is in the correct format.

We can use the regular expression to Validate Decimal Numbers in JavaScript. The regular expression for same is given below.

Regex for decimal in JavaScript:

const decimalNumber = /^-?\d*\.?\d+$/; 

Below are the approaches used to Validate Decimal Numbers in JavaScript:

Table of Content

  • Using the match() method
  • Using Regular Expression

Similar Reads

Validate Decimal Numbers using the match() method

The match() method is a built-in JavaScript method that allows you to match a string against a regular expression....

Validate Decimal Numbers using test()

...

Contact Us