How to Validate Decimal Numbers in JavaScript ?
Last Updated :
04 Mar, 2024
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) {
const isDecimal = input.match(/^-?\d*\.?\d+$/);
return isDecimal !== null ;
}
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) {
const decimalPattern = /^-?\d*\.?\d+$/;
return decimalPattern.test(input);
}
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!
Share your thoughts in the comments
Please Login to comment...