Vms
Vms

Reputation: 209

Regex in C# for password

I have regex for validating user passwords to contain:

  • atleast 8 alpha numberic characters
  • 1 uppercase letter
  • 1 lowercase letter
  • 1 digit

Allowed special charaters !@#$%*.~

I am using the following regex:

(?=(.*\w){8,})(?=(.*[A-Z]){1,})(?=(.*[a-z]){1,})(?=(.*[0-9]){1,})(?=(.*[!@#$%*.~]))

This however does not prevent the user from entering other special characters such as <,> , &.

How do I can restrict the allowed number of special characters?

Upvotes: 2

Views: 388

Answers (2)

Andrew Cheong
Andrew Cheong

Reputation: 30273

^(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z])[a-zA-Z0-9!@#$%*.~]{8,}$

The anchoring (^ and $) is important, by the way.

Upvotes: 1

Jason McCreary
Jason McCreary

Reputation: 72991

A single regex to validate everything will ultimately look like line noise.

Instead I suggest:

  • Use simple String functions to test length
  • Use Regex to test for character inclusion and validity

Upvotes: 3

Related Questions