0
  1. At least one lower case letter,
  2. At least one upper case letter,
  3. At least special character,
  4. At least one number
  5. At least 8 characters length

problem is showing error at "/d" in regx pattern

private void txtpassword_Leave(object sender, EventArgs e) {
    Regex pattern = new Regex("/^(?=.*[a-z])(?=.*[A-Z])(?=.*/d)(?=.*[#$@!%&*?])[A-Za-z/d#$@!%&*?]{10,12}$/");
    if (pattern.IsMatch(txtpassword.Text)) {
        MessageBox.Show("valid");
    } else {
        MessageBox.Show("Invalid");
        txtpassword.Focus();
    }
}
Mat
  • 202,337
  • 40
  • 393
  • 406
shayaaz
  • 13
  • 3
  • `/d`should be `\d`. – Marco Luzzara Jul 08 '18 at 08:11
  • If I were you, I would put each rule into a separated `Regex` object, and test your string against them each. This way, the rules are much easier to read, understand, maintain, and extend. – Lucas Jul 08 '18 at 09:46

2 Answers2

1

Try this instead :

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

Tests

Moien Tajik
  • 2,115
  • 2
  • 17
  • 39
  • Moien Tajik can you explain the code as i am new learning c# does this satisfying all the necessary things as above mentioned – shayaaz Jul 08 '18 at 10:02
  • @shayaaz Yeah, It's ok for all of your needs. If you visit the link I had mentioned and hover on regex characters, it will simply tell you what it does. And I have added UnitTests which proves it works correctly based on your needs. – Moien Tajik Jul 08 '18 at 12:46
0

In regex, the backslash is used to escape. So instead of /d it should have been \d.

But you could also just use [0-9] instead.

^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9\s])\S{8,}$

Also, when using backslashes in a string.
Then either double backslash. Or use a verbatim string. F.e. @"foobar"

More about that in this SO post.

Example C# code:

string[] strings = { "Foo!bar0", "foobar", "Foo bar 0!", "Foo!0" };

Regex rgx = new Regex(@"^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9\s])\S{8,}$");

foreach (var str in strings){
    Console.WriteLine("[{0}] {1} valid.", str, rgx.IsMatch(str) ? "is" : "is not");
}

Returns:

[Foo!bar0] is valid.
[foobar] is not valid.
[Foo bar 0!] is not valid.
[Foo!0] is not valid.
LukStorms
  • 28,916
  • 5
  • 31
  • 45