kevin janada
kevin janada

Reputation: 41

how to exclude character if a certain character occurs earlier

I'm trying to validate US telephone numbers and i'm trying to exclude 555)555-5555 and (555-555-5555

How do i exclude the '(' if there's no ')' after the 3rd 5 and vice versa?

Upvotes: 0

Views: 79

Answers (3)

Azad
Azad

Reputation: 5264

my suggestion is to auto format the number while entering it, see the demo below

$(function() {

  $('#us-phone-no').on('input', function() {

    var value = $(this).val();

    var nums = value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
    var formated = !nums[2] ? nums[1] : nums[1] + '-' + nums[2] + (nums[3] ? '-' + nums[3] : '');

    $(this).val(formated);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tetx" id="us-phone-no">

Upvotes: 1

MotKohn
MotKohn

Reputation: 3945

How about something simple: https://regex101.com/r/g6uBF4/1

^((\(\d{3}\))|(\d{3}-))\d{3}-\d{4}

Just test for each case separately. Either 3 digits enclosed in parenthesis (\d{3}\) or | 3 digits with a dash (\d{3}-). Then the rest of the number \d{3}-\d{4}.

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

In general, you can't use Javascript regexes to ensure that parentheses are correctly balanced if there can be an indefinite number of nested parentheses. You'd need recursive/balanced matching for that. But your case is not that complicated.

For example, you can add a negative lookahead assertion at the start of your regex:

/^(?![^()]*[()][^()]*$)REST_OF_REGEX_HERE/

This ensures that there won't be a single opening or closing parenthesis in your input.

Explanation:

^       # Start of string
(?!     # Assert that it's impossible to match...
 [^()]* #  any number of characters other than parentheses,
 [()]   #  then a single parenthesis,
 [^()]* #  then any number of characters other than parentheses,
 $      #  then the end of the string.
)       # End of lookahead

Of course there may be other ways to do what you need, but you didn't show us the rest of the rules you're using for matching.

Upvotes: 0

Related Questions