Allow only number and a single hypen between number

Viewed 52

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">

2 Answers

Your regex is okay, but you shouldn't use keypress event as the trigger, it always fires before anything is actually input. Use .on('input', ...) instead:

$('#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">

The following regex should do the trick:

const exp = /^\d+-\d+$/g;

const test1 = '1-1';
const test2 = '1%2';
const test3 = '1-a';
const test4 = '1234-8754332';
const test5 = '-5';

console.log(exp.test(test1)); // true
console.log(exp.test(test2)); // false
console.log(exp.test(test3)); // false
console.log(exp.test(test4)); // true
console.log(exp.test(test5)); // false

Related