alexiscrack3
alexiscrack3

Reputation: 148

Best way to validate a string in js

I need to make sure that my string is a number and for doing that, I was using isNaN function and everything was working but I got a problem when I typed in my input field '0e1'.

I was wondering what's the best way to check if my string is a number and without scientific notation

Upvotes: 0

Views: 185

Answers (4)

DaniKR
DaniKR

Reputation: 2448

isNaN() function determines whether a value is an illegal number, so if it is not a number. The good thing about isNaN function is, that is suportet by all browsers (ch, ie, ff, op, sf).

function myFunction() {
    var a = isNaN(123) + "<br>";
    var b = isNaN(-1.23) + "<br>";
    var c = isNaN(123-456) + "<br>";
    var d = isNaN("Hello") + "<br>";
    var e = isNaN("2014/11/19") + "<br>";

    var result = a + b + c + d + e;
    document.getElementById("test").innerHTML = result;
}

So result would be: If value is a number return "False" if is not a number return "True".

You can test it on JsFiddle: isNaN()

Upvotes: 0

Ian Hazzard
Ian Hazzard

Reputation: 7771

Actually, the method you are using is fine. You have one problem with your code:

isNaN() should be !isNaN(). Remember, isNaN() checks if the number is NotaNumber. `!isNaN() checks if it IS a number.

isNaN(0e1) should return false because 0e1 is a number! I know, it's kind of confusing.

!isNaN(0e1) will return TRUE because !isNan() checks if a value IS a number.

I hope this helps.

Upvotes: 0

Chris
Chris

Reputation: 2806

Try using regex. Here are some examples. The result is null if no match was found.

alert("0e1".match(/^[-+]?[0-9]*\.?[0-9]+$/))    // null
alert("1".match(/^[-+]?[0-9]*\.?[0-9]+$/))      // 1
alert("-1".match(/^[-+]?[0-9]*\.?[0-9]+$/))     // -1
alert("1.0".match(/^[-+]?[0-9]*\.?[0-9]+$/))    // 1.0
alert("-1.5".match(/^[-+]?[0-9]*\.?[0-9]+$/))   // -1.5
alert("-1.5 4".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // null

Upvotes: 2

Preston S
Preston S

Reputation: 2771

If you want your input to only be an integer or float do this instead;

var input = '0e1';

if(!isNaN(input) && (parseInt(input, 10).toString() == input || parseFloat(input).toString() == input)){
    //This is a valid number
}

Upvotes: 0

Related Questions