Open In App

How to Validate Decimal Numbers in JavaScript ?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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!

Validate Decimal Numbers using test()

You can directly use a regular expression to test if the input string is a valid decimal number.

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

Javascript




function validateDecimalNumberUsingRegExp(input) {
    // Define a regular expression for decimal numbers
    // This pattern allows for an optional negative sign, followed by digits, an optional decimal point, and more digits
    const decimalPattern = /^-?\d*\.?\d+$/;
 
    // Test if the input matches the pattern
    return decimalPattern.test(input);
}
 
// Example usage:
const userInput = "3.14";
if (validateDecimalNumberUsingRegExp(userInput)) {
    console.log("Approach 2: Valid decimal number!");
} else {
    console.log("Approach 2: Not a valid decimal number.");
}


Output

Approach 2: Valid decimal number!



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads