jquery中正十进制值和-1值的正则表达式

jquery中正十进制值和-1值的正则表达式,jquery,regex,Jquery,Regex,如何在jquery中创建正十进制值和-1值的正则表达式? 我设法用这个来计算正小数和负小数,但它只能是-1。有什么想法吗 $(".SermeCoopValidarTope").keypress(function (e) { var tecla = (document.all) ? e.keyCode : e.which; var numeroDecimal = $(this).val(); if (tecla == 8) return true; if (tec

如何在jquery中创建正十进制值和-1值的正则表达式? 我设法用这个来计算正小数和负小数,但它只能是-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
});
$(“.SermeCoopValidarTope”).keypress(函数(e){
var tecla=(document.all)?e.keyCode:e.which;
var numeroDecimal=$(this.val();
if(tecla==8)返回true;
如果(tecla>47&&tecla<58){
if(numeroDecimal==“”)返回true
regexp=/^([0-9])*[.]?[0-9]{0,1}$/;
返回(正则表达式测试(数值模拟))
}
如果(tecla==46){
if(numeroDecimal==“”)返回false
regexp=/^[0-9]+$/
返回regexp.test(数值模拟)
}
返回错误
});

使用或
|
和两个匹配表达式来测试是否匹配

我还重新编写了代码,根据当前值和新的按键来构造期望值。这大大简化了代码

$(".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:

正则表达式的简化版本(感谢@Brian Stephens):

句点小数分隔符:

逗号小数分隔符:


您可以使用
|
(或运算符):

另外,我建议您将regex
/^([0-9])*[.]?[0-9]{0,1}$/
更改为

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

为了使它更有意义,并且不允许像
123.
(以点结尾)或仅仅

这样的值,谢谢!但不允许我在文本框中键入“-”:原始代码的逻辑总是测试实际需求后面的一个字符。整个过程需要彻底检修才能完成真正需要的操作(允许-1或小数点后最多2位)。否则它允许双周期等。谢谢!但不允许我在我的TextBox@Eduardo佩德罗莎·巴雷罗:那是因为你只接受特定的按键,而忽略其他按键(包括减号=45)。只需将其添加到'if(tecla>47&&tecla<58 | | tecla==45){谢谢TrueBlueAussie,现在如果我输入'-'不允许我输入任何,也允许我输入一个数字和'-'例如:'3-'@Eduardo Pedrosa Barreo:太快了,老虎:)答案更新了。我重新编写了它,使其更简单。对不起,滥用:),最后一件事……我如何更改十进制分隔符?我想,'你有一个小模型来证明吗ide的一个完整测试?刚刚意识到当前的逻辑有点中断…我改变了逻辑,先创建预期的字符串,然后测试它。
/^(-1?|\d*.?\d{0,2})$/
/^(-1?|\d*,?\d{0,2})$/
/^([0-9]+|-1)$/ or simply /^(\d+|-1)$/
/^([0-9])*(\.[0-9])?$/ or simply /^\d*(\.\d)?$/