1

我想验证一个数字是否具有某些参数,例如我想确保一个数字有 3 个小数是正数。我在互联网上搜索了不同的地方,虽然我找不到如何去做。我已使该文本框仅接受数字。我只需要其余的功能。

谢谢,

$("#formEntDetalle").validate({
                    rules: {

                        tbCantidad: { required: true, number: true },
                        tbPrecioUnidad: { required: true, number: true },

                    }
                    messages: {

                        tbCantidad: { required: "Es Necesario Entrar una cantidad a la orden" },
                        tbPrecioUnidad: { required: "Es Necesario Entrar el valor valido para el producto" }

                    },
                    errorPlacement: function(error, element) {
                        parent = element.parent().parent();
                        errorPlace = parent.find(".errorCont");
                        errorPlace.append(error);
                    }
                });

我想用类似的东西来控制那个文本框:

$.validator.addMethod('Decimal',
                    function(value, element) {
                       //validate the number
                    }, "Please enter a correct number, format xxxx.xxx");
4

2 回答 2

15

基于此处的示例:

$.validator.addMethod('Decimal', function(value, element) {
    return this.optional(element) || /^\d+(\.\d{0,3})?$/.test(value); 
}, "Please enter a correct number, format xxxx.xxx");

或允许使用逗号:

$.validator.addMethod('Decimal', function(value, element) {
    return this.optional(element) || /^[0-9,]+(\.\d{0,3})?$/.test(value); 
}, "Please enter a correct number, format xxxx.xxx");
于 2012-04-10T14:10:49.340 回答
3

为了防止数字不能有小数,您可以使用以下内容:

// This will allow numbers with numbers and commas but not any decimal part
// Note, there are not any assurances that the commas are going to 
// be placed in valid locations; 23,45,333 would be accepted

/^[0-9,]+$/

要要求始终使用小数,您将删除 ? 这使得它是可选的,并且还要求数字字符 (\d) 的长度为 1 到 3 位:

/^[0-9,]+\.\d{1,3}$/

This is interpreted as match the beginning of the string (^) followed by one or more digits or comma characters. (The + character means one or more.)

Then match the . (dot) character which needed to be escaped with a backslash (\) due to '.' normally meaning one of anything.

Then match a digit but only 1-3 of them. Then the end of the string has to appear. ($)

Regular expressions are very powerful and great to learn. In general they will benefit you no matter what language you run into in the future. There are lots of great tutorials online and books you can get on the subject. Happy learning!

于 2012-04-10T18:18:57.980 回答