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

前端 未结 3 1838
醉话见心
醉话见心 2021-01-25 12:40

this is what I have so far:

$j(element)..keypress(function(e){
        var val = $j(this).val();
        if ((\"1234567890.\").indexOf(e.charCode) > -1){
             


        
相关标签:
3条回答
  • 2021-01-25 12:41

    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/

    0 讨论(0)
  • 2021-01-25 12:59

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

    0 讨论(0)
  • 2021-01-25 13:08

    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);
        }
    });
    
    0 讨论(0)
提交回复
热议问题