Marais Rossouw
Marais Rossouw

Reputation: 957

Input pattern matching

Seem's like a trivial question, but how do you test if the key you're about to input, could potentially fulfil the regex pattern.

For instance, I have a string that comes from server like AAA, which I loop over per char, and have a map object that looks something like:

{
    '9': /\d/,
    'A': /[a-zA-Z]/,
    '*': /[a-zA-Z0-9]/
}

Then I construct a regex from that AAA to, /^([a-zA-Z])?([a-zA-Z])?([a-zA-Z])?$/.. The reason the for optional flag, was to "fulfil" at any char, but no more than 3 chars.

Anyway, so on my keypress event I have this code:

function(e) {
    var val = e.target.value,
        thisPress = String.fromCharCode(e.keyCode),
        potential = val + thisPress;

    if (!potential.match(mask)) {
        e.preventDefault();
    }
}

Where mask is that regex (/^([a-zA-Z])?([a-zA-Z])?([a-zA-Z])?$/).

Which works, but that'll also fulfil, a, or ab, or abc, rather than being fully fulfilled once abc is entered. Would it be, just to wrap a couple more groups on there, maybe do string length matching or what..

Bear in mind, a potential combination would be like AA-AA_99, which would translate to /^[a-zA-Z][a-zA-Z]\-[a-zA-Z][a-zA-Z]\_[0-9][0-9]$/..

I know these regex statements aren't at all optimised, but it gives the ability for the users using the software to use it, without knowing regex. Even though its primitive.

Hope it all made sense.

Upvotes: 1

Views: 170

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

You can't use the same regex for both live validation (masking) and final input validation. Create 2 regexps: one that you have and another without ? modifier for final validation.

Use

var mask = /^([a-zA-Z])?([a-zA-Z])?([a-zA-Z])?$/;

to validate live input, and

var final = /^([a-zA-Z])([a-zA-Z])([a-zA-Z])$/; 

to validate final input.

Upvotes: 1

Related Questions