使用或|
与两个匹配的表达式来测试任一/或匹配。
我也重写了代码来构建基于当前值和新按键的期望值。这简化了代码。
$(".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})$/
你有这样一个小样机,以提供完整的测试反对? –
刚刚意识到当前的逻辑有点破碎......我改变了逻辑,先创建预期的字符串,然后测试它。 –