I’m trying to create partial RegEx match in JS. What I want to achieve is that when user enters something inside input field, JS will always do partial match for number sequence on key press, not only when whole RegEx match is fulfilled.
So, this is the RegEx rule:
^[12][^1-6]\d{2}$
When user enters number 1 or 2, that is correct match, but 3 is incorrect. Next, when numbers between 1 and 6 are not entered, that is also correct, and at last any 2 next numbers are correct. As I said, right now RegEx match is fulfilled only when all 4 numbers are entered.
How can I achieve partial input check?
Well, the easiest solution is to wrap optional components into the corresponding
(?:)?construct. You actually have two optional components, so you need to take that into account.The result will look like…
… as you have to match both ‘2x’, ‘2×1’, and ‘2×11’, it seems. ) Hence
{0,2}quantifier.The problem obviously is that you cannot use a single regex to check whether a user finished entering some value into your field – or not. In other words, if you want the ‘intermediate’
1to match, but the resulting1not to match, well, it’s just impossible to do with a single regex check. )