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!
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With