验证十进制数

时间:2012-04-10 14:06:26

标签: jquery validation decimal

我想验证一个数字是否有某些参数,例如我想确保一个数字有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");

2 个答案:

答案 0 :(得分:15)

基于示例here

$.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");

答案 1 :(得分: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}$/

这被解释为匹配字符串(^)的开头,后跟一个或多个数字或逗号字符。 (+字符表示一个或多个。)

然后匹配。 (点)由于'''而需要使用反斜杠(\)进行转义的字符。通常意味着什么。

然后匹配一个数字,但只有1-3个。 然后必须出现字符串的结尾。 ($)

正则表达式非常强大且易于学习。一般来说,无论您将来遇到什么语言,它们都会让您受益。网上有很多很棒的教程,你可以在这些主题上找到书籍。快乐学习!

相关问题