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

前端 未结 3 1840
醉话见心
醉话见心 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 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);
        }
    });
    

提交回复
热议问题