Check if a String is a Valid Number in JavaScript

How can I check if a string is a valid number in JavaScript, similar to the IsNumeric() function in VB6?

1 Like

With my experience, a simple and quick method is using JavaScript’s built-in isNaN() function to check if a string is a valid number. Essentially, if isNaN() returns false, it indicates the string is a valid number in JavaScript."_

function isValidNumber(str) {
    return !isNaN(str);
}

console.log(isValidNumber("123"));  // true
console.log(isValidNumber("abc"));  // false

This approach gives a straightforward way to check if a string is a number in JavaScript without diving into more complex logic.

I’ve found another effective approach is to use parseFloat() or parseInt(). With these functions, you can attempt to convert the string and then double-check if the result is a valid number with isNaN() and isFinite()."_

function isValidNumber(str) {
    const num = parseFloat(str);
    return !isNaN(num) && isFinite(num);
}

console.log(isValidNumber("123.45"));  // true
console.log(isValidNumber("abc"));     // false

In this method, the parsing functions add an extra layer by trying to convert the string first. This helps when you want to check if a string is a number in JavaScript, especially when dealing with decimals.

For cases where you need more precise control, you might consider using a regular expression. In my experience, regex gives you the ability to directly match a valid number format."_

function isValidNumber(str) {
    const regex = /^-?\d+(\.\d+)?$/;
    return regex.test(str);
}

console.log(isValidNumber("123"));      // true
console.log(isValidNumber("12.34"));    // true
console.log(isValidNumber("abc"));      // false

This regex approach is ideal if you need to account for more specific patterns like allowing negative numbers. It’s a great way to check if a string is a number in JavaScript using clear rules.