Jump to content

[SOLVED] Validate - numbers and decimals only for money field


Jason28

Recommended Posts

Found this through Google in about 3 seconds:

 

function IsNumeric(sText) {
    var ValidChars = "0123456789.";
    var IsNumber=true;
    var Char;

    for (i = 0; i < sText.length && IsNumber == true; i++) { 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }

    return IsNumber;
}

 

http://www.codetoad.com/javascript/isnumeric.asp

 

Adam

Link to comment
Share on other sites

Found this through Google in about 3 seconds:

 

function IsNumeric(sText) {
    var ValidChars = "0123456789.";
    var IsNumber=true;
    var Char;

    for (i = 0; i < sText.length && IsNumber == true; i++) { 
        Char = sText.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }

    return IsNumber;
}

 

http://www.codetoad.com/javascript/isnumeric.asp

 

Why would you want to loop through each character when there are much better alternatives? That function also has a bug in that it would accept input with multiple decimals.

 

Of course you could use the built-in function within JavaScript, isNaN(), which will return true if the value is not a number, else it returns false.

 

function valid_number(inputVal)
{
    return (!isNaN(inputVal));
}

 

Of course, if you're talking about a currency field you might also want to round to the nearest two decimal places. However, you can handle the problem of invalid input in a few different ways:remove non-numeric characters, remove all input if any character is not valid, etc. It's up to you.

Link to comment
Share on other sites

function valid_number(fieldObj)
{
    if (fieldObj.value!='' && isNaN(fieldObj.value))
    {
        alert('You must enter a valid number');
        fieldObj.select();
        fieldObj.focus();
        return false;
    }
    return true;
}

 

<input type="text" name="cost" id="cost" onchange="valid_number(this);">

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.