I am new to regular expression. I am looking/searching for a restriction that only allow a single hypen between numbers. I have found a sample formula of regex but I don't know why my code below still accepts a character.
What I want to achieve is
Output
1-1
something like that.
$('#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">