使用或|
與兩個匹配的表達式來測試任一/或匹配。
我也重寫了代碼來構建基於當前值和新按鍵的期望值。這簡化了代碼。
$(".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})$/
你有這樣一個小樣機,以提供完整的測試反對? –
剛剛意識到當前的邏輯有點破碎......我改變了邏輯,先創建預期的字符串,然後測試它。 –