2012-04-10 75 views
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); 
        } 
       }); 

我想控制该文本框与喜欢的东西:基于实例here

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

小数点后的数字是可选的还是强制的?换句话说,“123.4”还是“234”是一个有效的条目? – Blazemonger 2012-04-10 14:08:42

+0

他们是可选 – 2012-04-10 14:10:17

回答

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"); 
+0

我可以控制昏迷?例如99,999.999或999,999,999.999等数字? – 2012-04-10 14:12:29

+0

轻松添加。你不熟悉正则表达式吗? – Blazemonger 2012-04-10 14:13:02

+0

注意:这个正则表达式还允许空字符串或带有前导或尾随点的字符串,例如'.123'或'123.''。 – Geert 2012-04-10 14:13:10

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个。 然后字符串的结尾必须出现。 ($)

正则表达式非常强大,很好学习。总的来说,无论你将来遇到什么语言,他们都会受益。网上有很多精彩的教程,以及关于这个主题的书籍。快乐学习!