TAS
TAS

Reputation: 383

Limiting a textbox to digits OR one of two non repeating strings only using regular expressions

I am trying to constrain a textbox to either digits OR one of two special string cases: "na" or "tx". If digits exits in the input, "na" and "tx" are invalid and should not be allowed in the input box. if "na" or "tx" exists, digits should not be allowed.

I am very new to reg expressions but is it possible to construct this? Here is what I have so far:

event.sender.element.find("input").keyup(function () {
    this.value = this.value.replace(/((?!na)|([^0-9]))/g, '');
});

Using basic online examples, I know how to limit the input to purely digits. My current set of requirements, however, is making this very challenging for me.

Upvotes: 0

Views: 203

Answers (2)

FiLeVeR10
FiLeVeR10

Reputation: 2165

$('input').keyup(function () {
    var a = $(this).val();
    if (a.match(/^tx/)) {
        a = 'tx';//set manually
    } else if (a.match(/^na/)) {
        a = 'na';//set manually
    } else if(a.match(/[\d]/)) {
        a = a.replace(/[^0-9]+/g, '');//replace all but numbers
    } else if (a.match(/^[nt]/)) {
       a = a.replace(/^([tn])([a-zA-Z])+$/,'$1');//replace with first letter
    } else {
        a = '';//matches nothing equals nothing
    }
    $(this).val(a);//print new value
})

It uses regex to remove any undesired input, and provides reporting on the demo. If it doesn't start with 'tx' or 'na', but does have a number it switches to number mode, and if it does begin with either of them then it's hard set to them. If nothing matches, it empties out.

EDIT

Although my answer produced the correct result, it wasn't as simple as it should be with regex.

So I added Wrikkens regex as well, since it's easier: http://jsfiddle.net/filever10/FQ5aD/

The biggest difference i see in functionality is with strings like "t5", on wrikkens, that gets changed to "t", and on mine that triggers number mode and will change to "5".

This allows it to fit the parameters of the problem. Since neither 'tx' or 'na' exist at that point, numbers should take over because 't' and 'n' don't match anything yet, but a number does; since it only needs one character to match as a number, and the others need 2 for a match.

Upvotes: -1

Wrikken
Wrikken

Reputation: 70460

string = string.replace(/^(n(a?|$)|t(x?|$)|[0-9]*).*$/g,'$1');

Though, generally, using onkeypress & onchange events in tandom yield better results: the first prevents the 'flickering' of the invalid characters, the second prevents changing it by pasting in data with the mouse for instance. See also: How to prevent number input on keydown As always: revalidate it on the server.

Upvotes: 2

Related Questions