2015-04-28 63 views
2

在jQuery中正數十進制值和-1值的正則表達式如何? 我設法做到這一點爲正數和負數十進制值,但它只能是-1。任何想法?在jquery中的正數十進制值和-1值的正則表達式

$(".SermeCoopValidarTope").keypress(function (e) { 
    var tecla = (document.all) ? e.keyCode : e.which; 
    var numeroDecimal = $(this).val(); 
    if (tecla == 8) return true; 

    if (tecla > 47 && tecla < 58) { 
     if (numeroDecimal == "") return true 
     regexp = /^([0-9])*[.]?[0-9]{0,1}$/; 
     return (regexp.test(numeroDecimal)) 
    } 
    if (tecla == 46) { 
     if (numeroDecimal == "") return false 
     regexp = /^[0-9]+$/ 
     return regexp.test(numeroDecimal) 
    } 
    return false 
}); 
+0

你有這樣一個小樣機,以提供完整的測試反對? –

+0

剛剛意識到當前的邏輯有點破碎......我改變了邏輯,先創建預期的字符串,然後測試它。 –

回答

2

使用或|與兩個匹配的表達式來測試任一/或匹配。

我也重寫了代碼來構建基於當前值和新按鍵的期望值。這簡化了代碼。

$(".SermeCoopValidarTope").keypress(function (e) { 
    var tecla = (document.all) ? e.keyCode : e.which; 

    var numeroDecimal = $(this).val(); 

    // Allow backspace 
    if (tecla == 8) return true; 

    // if it's a valid character, append it to the value 
    if ((tecla > 47 && tecla < 58) || tecla == 45 || tecla == 46) { 
     numeroDecimal += String.fromCharCode(tecla) 
    } 
    else return false; 

    // Now test to see if the result "will" be valid (if the key were allowed) 

    regexp = /^\-1?$|^([0-9])*[.]?[0-9]{0,2}$/; 
    return (regexp.test(numeroDecimal)); 
}); 

的jsfiddle:http://jsfiddle.net/TrueBlueAussie/Ld3n4b56/

更新支持,而不是.爲小數分隔:

$(".SermeCoopValidarTope").keypress(function (e) { 
    var tecla = (document.all) ? e.keyCode : e.which; 

    var numeroDecimal = $(this).val(); 

    // Allow backspace 
    if (tecla == 8) return true; 

    // if it's a valid character, append it to the value 
    if ((tecla > 47 && tecla < 58) || tecla == 45 || tecla == 44) { 
     numeroDecimal += String.fromCharCode(tecla) 
    } 
    else return false; 

    // Now test to seee of the result will be valid 

    regexp = /^\-1?$|^([0-9])*[,]?[0-9]{0,2}$/; 
    return (regexp.test(numeroDecimal)); 
}); 

的jsfiddle:http://jsfiddle.net/TrueBlueAussie/Ld3n4b56/1/

縮短版本正則表達式(感謝@布賴恩·斯蒂芬斯):

期小數分隔:http://jsfiddle.net/Ld3n4b56/4/

/^(-1?|\d*.?\d{0,2})$/ 

逗號小數點分隔符:http://jsfiddle.net/Ld3n4b56/3/

/^(-1?|\d*,?\d{0,2})$/ 
+0

謝謝!但不允許我在文本框中輸入' - ' – kowalcyck

+0

@Eduardo Pedrosa Barrero:這是因爲您只接受特定的按鍵並忽略其餘(包括minus = 45)。只要將它添加到'if(tecla> 47 && tecla <58 || tecla == 45){ –

+0

}感謝TrueBlueAussie,現在如果我鍵入' - '不允許輸入任何內容,還允許輸入數字, ' - '示例:'3-' – kowalcyck

1

可以使用|(或運營商):

/^([0-9]+|-1)$/ or simply /^(\d+|-1)$/ 

另外我建議你去查查NGE您正則表達式/^([0-9])*[.]?[0-9]{0,1}$/

/^([0-9])*(\.[0-9])?$/ or simply /^\d*(\.\d)?$/ 

爲了使之更有意義,並不允許像123.值(用點結束),或者只是.

+0

謝謝!但不允許我在我的文本框中鍵入' - ': – kowalcyck

+0

原始代碼的邏輯總是在*實際要求後面測試*一個字符。整個事情需要徹底檢查,以便做到真正需要的東西(允許-1或小數點後兩位小數)。否則它允許雙重時間等。 –