Everyone may experience this requirement when we creating
new password,
- At least one
lower case letter,
- At least one
upper case letter,
- At least
special character,
- At least one
number
- At least 8
characters length
So we can achieve this one in two ways
- Using regular
expressions
- Using C# code
Using Regular Expressions
Refer this link for basics of Regular Expression Syntaxes
In Asp.net we have RegularExpressionValidator control..
- Use one text
box with one button
- Declare the
RequiredFieldValidator
- Declare the
RegularExpressionvalidation
Important Properties
of Regular Expression Validator:
- ErrorMessage
- ValidationExpression
- ControlToValidate
This> "^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!*@#$%^&+=]).*$" validation expression fulfills the above
requirement.
- <table>
- <tr>
- <td>
- <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please Enter password"
- ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
- <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="RegularExpressionValidator"
- ValidationExpression="^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!*@#$%^&+=]).*$"
- ControlToValidate="TextBox1"></asp:RegularExpressionValidator>
- </td>
- </tr>
- <tr>
- <td>
- <asp:Button ID="Button1" runat="server" Text="Button" />
- </td>
- </tr>
- </table>
Using C#
code:
One of our
community guy (Vulpes) suggested this code to achieve the requirement…
If above any
three conditions are satisfied then the creation of password is successful..
C# Code is:
- using System;
- class Test
- {
- static void Main()
- {
- string[] passWords = {"aX2#", "sed2T", "*v3X", "Ae234&B", "fg234", "g1HL","#1$23", "5a7%"};
- foreach(string passWord in passWords)
- {
- bool b = ValidatePassword(passWord);
- Console.WriteLine("'{0}' is{1} a valid password", passWord, b ? "": "n't");
- }
- Console.ReadKey();
- }
- static bool ValidatePassword(string passWord)
- {
- int validConditions = 0;
- foreach(char c in passWord)
- {
- if (c >= 'a' && c <= 'z')
- {
- validConditions++;
- break;
- }
- }
- foreach(char c in passWord)
- {
- if (c >= 'A' && c <= 'Z')
- {
- validConditions++;
- break;
- }
- }
- if (validConditions == 0) return false;
- foreach(char c in passWord)
- {
- if (c >= '0' && c <= '9')
- {
- validConditions++;
- break;
- }
- }
- if (validConditions == 1) return false;
- if(validConditions == 2)
- {
- char[] special = {'@', '#', '$', '%', '^', '&', '+', '='};
- if (passWord.IndexOfAny(special) == -1) return false;
- }
- return true;
- }
- }
That's it……Need
any clarifications send me a message