2012-04-10 110 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個。 然後字符串的結尾必須出現。 ($)

正則表達式非常強大,很好學習。總的來說,無論你將來遇到什麼語言,他們都會受益。網上有很多精彩的教程,以及關於這個主題的書籍。快樂學習!