2015-04-28 65 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或小数点后两位小数)。否则它允许双重时间等。 –