我的正则表达式的某些部分不起作用

时间:2017-05-15 13:35:39

标签: javascript jquery regex

我正在尝试使用正则表达式验证文本框上的输入

表达式应该只允许数字,最多两位小数,最多一位逗号(,)和数字前面的一个减号(可选)。

有效:

  • 0,25
  • 10,2
  • -7000
  • -175,33
  • 15555555555555,99

无效:

  • 9999
  • 15.03
  • 77,77,77

我正在使用^[-+]?[\d ]+(,\d{0,2})?$ 正则表达式用在Jquery代码中以防止用户输入无效数字(event.preventDefault()):

    $("input[name*='TB_mytbx']").on('keypress', function (event) {
        var regex = new RegExp("^[-+]?[\d ]+(,\d{0,2})?$", "g");
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
            event.preventDefault();
            return false;
        }
    });

只有正则表达式的一部分似乎有效。

它适用于数字(它不允许我输入字母)但它也不允许使用逗号(,)和减号( - )。

我做错了什么?

修改

在我使用之前:

    if (focused.val().indexOf(',') != -1) {
    var number = (focused.val().split(','));
    if (number[1] && number[1].length >= 2) {
        event.preventDefault();
        return;
    }

但这会产生烦人的行为。只要输入两位数字,就不能再进行编辑了。例如:你不能改变200,50到300,50或100 300,50。 (你明白了)。我希望正则表达式能以某种方式改变它。

2 个答案:

答案 0 :(得分:2)

我认为你大规模过度复杂的正则表达式。这应该是充足的:

^-?\d+(,\d\d)?$
  • ^行首,
  • -?可选减号,
  • \d+后面跟着一堆数字,
  • (,\d\d)?后跟逗号和2位数字,均为3个可选项 (替代方案:(,\d{2})?
  • $行尾。



var regex = /^-?\d+(,\d\d)?$/;

console.log(regex.test('0,25'));
console.log(regex.test('-175,33'));
console.log(regex.test('15555555555555,99'));

console.log(regex.test('9,999'));
console.log(regex.test('15.03'));
console.log(regex.test('77,77,77'));




你有一个正则表达式来验证输入值 现在,该代码块可以替换为:

$("input[name*='TB_mytbx']").on('keypress', function (event) {
    var regex = /^-?\d+(,\d\d)?$/;
    var value = $(this).val();  // Use the field's value, instead of the pressed key.

    if (!regex.test(value)) {
        event.preventDefault();
        return false;
    }
});

答案 1 :(得分:0)

对于那些想知道的人,我使用此代码解决了它

        $("input[name*='mythingy']").on('keypress', function (event) {
        var theEvent = event || window.event;
        var key = theEvent.keyCode || theEvent.which;
        key = String.fromCharCode(key);
        var value = this.value;
        var value = value.replace(value.substring(theEvent.currentTarget.selectionStart, theEvent.currentTarget.selectionEnd), "");
        value = [value.slice(0, theEvent.currentTarget.selectionStart), key, value.slice(theEvent.currentTarget.selectionStart)].join('');
        var regex = /^[-+]?([\d ]+(,\d{0,2})?)?$/;
        if (!regex.test(value)) {
            theEvent.returnValue = false;
            if (theEvent.preventDefault) theEvent.preventDefault();
        }
    });