John
John

Reputation: 1499

RegEx to allow 12 or 13 digits

In my MVC application I define validation using the following RegEx

[RegularExpression(@"\d{8}0[1-2]\d{3}", ErrorMessage = "Must be numeric, 12 or 13 characters long & Format xxxxxxxx[01 or 02]xxx")]

But I want to allow 12 or 13 characters. The d{3} appears to be forcing that overall I have 13 characters input

To allow it to accept 12 or 13, I have changed d{3} to d{2} and its accepting 12 now.

But - can I be sure it will still take 13 characters?

Upvotes: 1

Views: 496

Answers (1)

Tushar
Tushar

Reputation: 87203

Must be numeric, 12 or 13 characters long & Format xxxxxxxx[01 or 02]xxx

To allow digits 1 or 2 after first nine digits,

^\d{8}0[12]\d{2,3}$
       ^^^^         : Allow 1 or 2 after `0`
           ^^^^^^^  : Any two or three digits

Note that [12] can also be written as (1|2) using OR/alteration.

Demo

Upvotes: 2

Related Questions