Strawberry
Strawberry

Reputation: 119

MVC Regex model validation

I want to have at least 3 numbers in my password. This validation always fails :

 [RegularExpression(@"[\d]{3}", ErrorMessage ="Password must have at least 3 digits")]
        [Display(Name = "NewPassword", ResourceType = typeof(ModelResources))]
        public string NewPassword { get; set; }

I have also tried with () in the expression. What am I doing wrong?

Upvotes: 1

Views: 65

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

To require at least three digits, you may use

"^([^0-9]*[0-9]){3}.*$" 

or

@"^(?:\D*\d){3}.*$" 

or the least effecient regex:

^(.*\d){3}.*$

See regex demo

Note that in .NET \d matches more than just [0-9] digits, it can match Arabic and other digits. The [^0-9] and \D matches any character but a digit.

  • ^ - start of string
  • ([^0-9]*[0-9]){3} - exactly 3 occurrences of 0 or more sequences of
    • [^0-9]* (or \D*) 0 or more characters other than a digit
    • [0-9] (or \d) - a digit
  • .* - 0 or more characters other than a newline
  • $ - end of string

Please note that using opposite character classes to match 3 digits follows the principle of contrast, which is very effecient compared to dot matching as it involves much less backtracking. You can check for yourself at regex101.com at regex debugger section: it takes 2 backtracking steps for my regex to complete matching and it takes ^(.*\d){3}.*$ ~180 steps to complete matching in the same string.

Upvotes: 1

Related Questions