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

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.

Thanks mjdamato, could you also give me the code to place in the html form that is used with this function?  I tried adding:

 

onClick="javascript:valid_number('item_price');"

 

to the form field but not sure if that is the one to use.

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);">

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.