-1

I have a simple regex data annotation

[RegularExpression(@"\d{5}", ErrorMessage = "Zipcode must be exactly 5 digits")]
public string Zipcode
{
    get;set;
}

When the value of the Zipcode is "12345"

Model.IsValid returns false.

Serge
  • 40,935
  • 4
  • 18
  • 45
Ajay S
  • 54
  • 5

1 Answers1

1

Try this it is used for validation Zip code. The Zip code should contain 5 digits and should not be 00000. [RegularExpression(@"^(?!00000)[0-9]{5,5}$", ErrorMessage = "Zip code should contain 5 digits")]

Serge
  • 40,935
  • 4
  • 18
  • 45
  • Thank you for your response. I gave Zipcode as an example. My requirement is that, string should have 5 digits. The regex works in a console app with regex.match however in razor pages the model is invalid with the same regex. – Ajay S Oct 21 '20 at 18:01
  • Try this [RegularExpression(@"^(\d{5})$", ErrorMessage = "error Message")] It is usually used in DataAnnotations instead directily. – Serge Oct 21 '20 at 18:03
  • Thank you that worked. Still curious why the original regex worked in a console app but not while validating the model. – Ajay S Oct 21 '20 at 19:02
  • I guess this is because it uses different name spaces. – Serge Oct 21 '20 at 19:03
  • Appreciate your help. – Ajay S Oct 21 '20 at 19:14
  • Thanks. My pleasure. – Serge Oct 21 '20 at 19:16