Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression to validate multiple condition

I require to validate a string using javascript with multiple conditions. I am not sure how to do this using regular expressions.

I need to check if the string does not contain any of the following conditions

Condition 1: String of any length beginning with 18XX or 1-8XX or 8XX, where X is any number from 0 to 9 (both 0 and 9 being inclusive). Ex: 1800abc, 812abc-def, 1-805-999-9999

Condition 2: The string beginning with NXX or 1NXX or 1-NXX followed by exactly seven numbers not including hyphens, where N is any number from 2 to 9 (both 2 and 9 being inclusive) and X is any number from 0 to 9 (both 0 and 9 being inclusive). Ex: 12-999-9999, 19009998888, 1-212---1-2-3-4-5-6-7--

Condition 3: The string beginning with XXXXX, where X is any number from 0 to 9 (both 0 and 9 being inclusive). Ex: 20176, 90210-Melrose

like image 512
Abishek Avatar asked Nov 27 '25 14:11

Abishek


1 Answers

you cannot have a single regex match all this, Er may be you can!! see below

try using these three for each condition, check for all three and pass only those that do not match any.

condition 1: ^1?-?8\d{2}.*$

condition 2: remove all hypens first then match for ^1?[2-9]\d{7}$

condition 3: ^\d{5}.*$

hope this helps

EDIT

You may have a single regex that can match this. since - seems to be an optional character lets remove them first, but as pointed out by @nnnnn in the comments, lets first check if the string actually begins with a - if it does then the string passes validation without further checks. then you can string those three together with | form a single regex which you can check against

^1?8\d{2}.*|1?[2-9]\d{7}|\d{5}.*

i removed -? from the first part since we've already removed all hypens.

like image 190
mzzzzb Avatar answered Nov 29 '25 03:11

mzzzzb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!