HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Foolproof number validation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numbervalidationfoolproof

Problem

I know there have been a lot of post, blog article answer on Stack Overflow (but the validation does return true on a tab character) about this. But I'm still looking for a neat way to validate if a value is a number.

I wrote the following. Does that cover the 99% of the cases? Is there a better way to do that?

function validateNumber(valueToCheck){
    var checkSum = 0;
    var isValid = true;

    if(typeof valueToCheck === "number"){
        return true;
    }
    if(typeof valueToCheck === "string"){
        if(valueToCheck.replace(/ /g,'') !== valueToCheck){
            return false;
        }

        if(valueToCheck.charAt(0) == '-'){
            valueToCheck = valueToCheck.substr(1); // remove minus sign
        }
        valueToCheck = valueToCheck.replace('.',''); // allow one decimal point

    }

    for(var i=0;i= 48 && valueToCheck.charCodeAt(i) <= 57)){
            isValid = false;
            break;
        }
    }

    return isValid;
}


Here is the jsfiddle with tests cases.

Solution

Personally I'm not sure why you're working so hard...

function validateNumber(valueToCheck) {
    return !isNaN(Number(valueToCheck));
}


or the more complete version from the question you've linked:

function validateNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}


JavaScript already has a number parser.

This will allow values like '42', '1.456', '1.456e3', [42], etc. All valid Numbers.

And it passes your test suite better than the original: http://jsfiddle.net/nL4L13k2/4/ and http://jsfiddle.net/nL4L13k2/5/

Code Snippets

function validateNumber(valueToCheck) {
    return !isNaN(Number(valueToCheck));
}
function validateNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

Context

StackExchange Code Review Q#71416, answer score: 13

Revisions (0)

No revisions yet.