Dan
Dan

Reputation: 4663

Check if string contains at least one of each: lowercase letter, uppercase letter, number, and special character

I've searched SO and Google and most examples I find don't seem to work as intended (or don't combine all of these elements). I'm trying to create a Regex expression that matches (passes) if a string contains at least one of the following anywhere in the string and fails if it is missing any of them:

This is what I've tried:

if (System.Text.RegularExpressions.Regex.IsMatch(txtTest.Text.Trim(), "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?^[[email protected]]).{8,}$"))
{
    lblMsg.Text = "Pass";
}
else
{
    lblMsg.Text = "Fail";
}

The problem is that this isn't working as intended. The following Pass when they should Fail (they don't have special characters):

It seems to work fine for detecting all but special characters. What did I do wrong and how do I fix it?

Upvotes: 3

Views: 5699

Answers (2)

Cornelius J. van Dyk
Cornelius J. van Dyk

Reputation: 728

While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:

  1. Add the https://www.nuget.org/packages/Extensions.cs package to your project.
  2. Add "using Extensions;" to the top of your code.
  3. "Smith23@".IsStrong() will return True whereas "Smith23".IsStrong() will return False.
  4. Every other check in the rest of the code is simply MyString.IsStrong(). By default .IsStrong() validates that all 4 components are used in the strong string, but if you wanted to use just 3 of the 4, you could do so like this MyString.IsStrong(3).

Your example code would become as simple as:

using Extensions;

//if (System.Text.RegularExpressions.Regex.IsMatch(txtTest.Text.Trim(), "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?^[[email protected]]).{8,}$"))
if (txtTest.Text.Trim().IsStrong())
{
    lblMsg.Text = "Pass";
}
else
{
    lblMsg.Text = "Fail";
}

Upvotes: 1

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

Change (?=.*?^[[email protected]]) with the below one:

       + see here
(?=.*?[^[email protected]])
                 ^^ i kept the dot, hyphen, etc as you used, if you don't need, remove.

In this regex, the ^ inside the character class [] is negating the characters. You were almost there, just unfortunately you have placed that outside the []

Upvotes: 13

Related Questions