1

I am trying to check to see if my string only have numbers or decimals in it using JavaScript.

If it has only numbers or decimals in the string then it should pass else it want to display a alert saying there is a error.

I have tried using the following code but it doesn't alert anything..

Am I doing something wrong?

var myString = "abc"; 

        if (myString.matches("[0-9].") && myString.length() > 2) 
        {
            alert("Pass");
        }
        else
        {
            alert("Error");
        }
1
  • 2
    length is not a function... so that's why nothing was happening. mystring.length > 2 Commented Nov 8, 2012 at 7:03

5 Answers 5

1

Let's simplify :-)

 if (/^[\d\.]{3,}$/.test(myString)) {
    alert("Pass");
 } else {
    alert("Error");
 }
Sign up to request clarification or add additional context in comments.

3 Comments

Lol just noticed that I put d{2,} too, and changed it as well.
If I make myString = "12.3" it displays Error where decimals should be allowed as well as 0-9
Note: there may be a problems, cause text 1..2 will match too. Use something more complex like: \d+(\.\d+)? and then make check your string length
1

use ^\d*[0-9](\.\d*[0-9])?$

DEMO

if (myString.match(/^\d*[0-9](\.\d*[0-9])?$/) && myString.length > 2) {
        alert("Pass");
    } else {
        alert("Error");
    }

Comments

0

Try:

/^\d+$/.test(myString)

Returns a boolean instead of an array or null, which is what match does. Altogether:

if (/^\d{2,}$/.test(myString)){ 
...
}else{
...
}

Comments

0

You could put it all together like this:

alert( /^\d{3,}$/.test( myString ) ? 'Pass' : 'Error' ) 

Comments

0

Your code is wrong myString.length() is a function not actually a length of myString

var myString = "abc"; 

    if (myString.match(/[0-9]/, "g") && myString.length > 2) 
    {
        alert("Pass");
    }
    else
    {
        alert("Error");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.