Password Validation in C#

Today, you will learn how to create a password validation textbox in c#. This procedure illustrates how to validate a textbox at least 8 to 15 charters and it's composed of at least one upper case and numbers. This is very helpful for you when you have to restrict your textbox password.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application for c#. ps1

Step 2

Do the form just like shown below. ps2

Step 3

Press F7 to open the code editor. In the code editor, add a namespace to access regular expression libraries.
  1.  
  2. using System.Text.RegularExpressions;

Step 4

Create a method for password validation.
  1.    
  2.         private static Regex PasswordValidation()
  3.         {
  4.             string pattern = "(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,15})$";
  5.  
  6.             return new Regex(pattern, RegexOptions.IgnoreCase);
  7.         }

Step 5

Initialize the method that you have created.
  1.    
  2.         static Regex vaildate_password = PasswordValidation();

Step 6

Write the following code to verify a password in a textbox when the button is clicked.
  1.      
  2.         private void button1_Click(object sender, EventArgs e)
  3.         {
  4.             if (vaildate_password.IsMatch(textBox1.Text) != true)
  5.             {
  6.                 MessageBox.Show("Password must be atleast 8 to 15 characters. It contains atleast one Upper case and numbers.", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  7.                 textBox1.Focus();
  8.                 return;
  9.             }
  10.             else
  11.             {
  12.                 MessageBox.Show("Password is correct.");
  13.             }
  14.         }
For any questions about this article. You can contact me @ Email – [email protected] Mobile No. – 09305235027 – TNT Or feel free to comment below.

Add new comment