NullVoxPopuli
NullVoxPopuli

Reputation: 65103

How do I validate a decimal field with jquery and regex?

this is what I have so far:

$j(element)..keypress(function(e){
        var val = $j(this).val();
        if (("1234567890.").indexOf(e.charCode) > -1){
            if (val.length > 0){
                var regex = /(\+|-)?(\d*\.\d*)/;
                if (regex.test(val)){
                    return true;
                } else {
                    return false;
                }       
            } else {
                return true;
            }
        } else {
            return false;
        }
    });

but for some reason, the text field only allows one character... and not even a number

Upvotes: 1

Views: 12562

Answers (3)

NullVoxPopuli
NullVoxPopuli

Reputation: 65103

With the help of @elclanrs and @mgibsonbr, I came to this:

$j = jQuery.noConflict();
$j(function() {
    $j("input").keypress(function(e) {
        var val = $j(this).val();
        var regex = /^(\+|-)?(\d*\.?\d*)$/;
        if (regex.test(val + String.fromCharCode(e.charCode))) {
            return true;
        }
        return false;
    });
});

which can be tested here: http://jsfiddle.net/9U2Mw/5/

Upvotes: 2

mgibsonbr
mgibsonbr

Reputation: 22007

First, shouldn't the return be the opposite? true if the test succeeds, false otherwise?

Second, . in a regex means "any character". If you want to match just a dot, use \.

This way your regex will work. However, for a better result, use the regex provided by elclanrs.

Note: it seems the value still hasn't changed when the keypress runs, so it's the old value that is being matched, not the new one.

Update: this is not an ideal solution, but will work nonetheless - You can use the code in this question to watch for changes in the input's value (it uses polling, though):

$(element).watch("value", function(propName, oldVal, newVal) {
    var regex = /^(\d*\.?\d*)$/;
    if (!regex.test(newVal)){
        $(this).val(oldVal);
    }
});

Upvotes: 2

elclanrs
elclanrs

Reputation: 94101

This checks a decimal number, with an optional +/- sign character. Found under 5sec in google. /^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/

Upvotes: 2

Related Questions