0

My Requirement:

I have to allow any string input in a textBox but it should not contain a 10 digit number in either of following formats:

dddddddddd

OR

dddddd-dddd

The regular expression which I have used is I have used is

^((?!\d{10})(?!\d{6}-\d{4}).)*$

It works fine but does not allow an input of more than 10 digits also.

Jai
  • 13
  • 3

1 Answers1

1

The ((?!\d{10})(?!\d{6}-\d{4}).)* is a tempered greedy token that matches any char, 0 or more times, that does not start a 10-digit or 6-digit+-+4-digit char sequences. It "disallows" a string to contain these patterns.

You can use

^(?!\d{6}-?\d{4}$).*$

See the regex demo.

Details

  • ^ - start of the string
  • (?!\d{6}-?\d{4}$) - a negative lookahead that fails the match if the whole string is either 10 digits, with an optional - between the 6th and the 7th digit
  • .*$ - the rest of the string.

NOTE: you do not need $ at the end, actually, but you may keep it for additional clarity. .* matches to the end of the line by default, and if there can be no line breaks, the $ is totally redundant.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563