Custom Regex format for ######-##

Viewed 71

I am absolutely clueless when it comes to Regex strings. I am trying to create a custom validator on a model using [RegularExpression("myValidator")] How can I create a regex expression to validate the following formats

  • ######-##
  • ######-#

where # is a number. Could someone help me out?

Thanks!

1 Answers
  • \d means digit.
  • {N} means previous symbol repeated N times

so, basically you want:

\d{6}-\d{2}

which would match 6 digits, a dash, and 2 more digits.

You can also do:

\d{6}-\d{1,2}

which would match 6 digits, a dash, and then 1 or 2 more digits, and therefore work for either format you described.

Related