javascript - 仅允许数字和数字之间的单个连字符

标签 javascript jquery regex

我是正则表达式的新手。我正在寻找/搜索仅允许数字之间有一个连字符的限制。我找到了正则表达式的示例公式,但我不知道为什么下面的代码仍然接受字符。

我想要实现的是

输出

1-1

类似的东西。

    $('#txt').keypress(function () {
        const exp = /^\d{1,2}(-\d{1,2})?$/;
        const el = $(this);
        if (exp.test(el.val()) == true)
            alert("a");
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txt">

最佳答案

您的正则表达式没问题,但您不应该使用 keypress 事件作为触发器,它总是在实际输入任何内容之前触发。使用 .on('input', ...) 代替:

$('#txt').on('input', function () {
    const exp = /^\d{1,2}(-\d{1,2})?$/;
    const el = $(this);
    
    // replace anything that is not a number or hyphan
    el.val(el.val().replace(/[^\d-]|(?<=^|-.*)-|(?<=\d{2,})\d/g, ''));
    
    if (exp.test(el.val()) == true)
        console.log("a");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txt">

关于javascript - 仅允许数字和数字之间的单个连字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64797145/

相关文章:

jquery - 如何在提交表单后再次运行 jQuery 验证器代码?

Java Camel 大小写撇号问题

java - 正则表达式保留空输入

c++ - 表达式 : string iterator not dereferencable while using boost regex

javascript - 由于 javascript,@font-face 无法加载某些请求?

javascript onclick 函数放大文本

javascript - 使用each函数将结果传递给另一个函数

javascript - Coffeescript 编译变体(coffeescript.org 与 Coffee-rails)

javascript - dojo声明构造函数: object member reference undefined

jquery - 简单的 jQuery Ajax 调用会泄漏 Internet Explorer 中的内存