allowing input only for float number

后端 未结 7 541
别那么骄傲
别那么骄傲 2020-12-09 21:58

I have pain-time when making input that only allows float number with jquery library. my code can\'t prevent chacacter \".\" when it\'s becoming first input, can anyone guid

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 22:38

    Regular expression would be my recommendation as well. If the value is being passed as a number and not a string you can use .toString to change it to a string and validate it with regular expression. For example:

    var str = value.toString();
    if(!str.match(/^-?[0-9]*[.][0-9]+$/)) {
        alert("Value must be a float number");
        return;
    }
    return value;
    

    The above regex will match if the value passed is a floating point number. It accepts both negative and positive numbers. If you only want to accept positive numbers simply remove the '-?' from the expression. It will also fail if the value is simply zero '0' without any decimal point. If you want to accept zero simply add it as a condition to the 'if' statement.

    You can use the above validation and an onchange event to prevent the user from entering a non-flot number.

提交回复
热议问题