Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - evaluating multiple regular expressions on one line

I'm fairly new to regular expressions in Javascript and I'm trying and failing to do something that seems simple. Basically, I need to evaluate whether a string meets 1 of 2 regular expression conditions. Basically, an input string can have 1 of 2 forms, and either of those is valid and anything else whatsoever is invalid.

So say I have 2 regular expressions: a= ^[0-9]\d{3}$ and b= ^1-\d{5} and want to see if an input string matches either before continuing. What I want to do is something like this:

If((!a.test(input)) || (!b.test(input)))
{
   alert("Invalid ID");
}

I've also tried a variation using the "|" operator:

if((!a|!b.test(input)))

But so far nothing has worked. Usually I get the statement to validate 1 or none of them, but never both. I'm not sure what I'm doing wrong here.

Thank you!

like image 739
ewomack Avatar asked Mar 27 '26 06:03

ewomack


1 Answers

I think your boolean logic is wrong. To match one or the other before proceeding, the failure case is when it doesn't match both of the tests like this:

if(!a.test(input) && !b.test(input))
{
   alert("Invalid ID");
}

Also, your If should be if with a lowercase i and I removed an unnecessary level of parentheses to make it a little easier to read.

You could also combine both your regexes into one and test it at once:

var re = /^[0-9]\d{3}$|^1-\d{5}/;

if (!re.test(input)) {
    alert("Invalid ID");
}

Also, you don't show the real code, but regular expressions are not declared how you have them in your question. Perhaps this is just how you copied them to the question, but they use the /regex here/ syntax which would be:

var a = /^[0-9]\d{3}$/;
var b = /^1-\d{5}/;

Note: On your second regex, do you intend for it to have a $ at the end like the first one?

like image 58
jfriend00 Avatar answered Mar 28 '26 20:03

jfriend00