CustomValidator - Client and Server side example - July 2009
.NET 3.x ASP.NET
A pattern regex was needed for the common password requirements. The original
solution was a regular expression validator however this did not work in IE7. As
it turns out the RegularExpressionValidator RegEx does not work properly in IE7,
in all cases, thus the custom validator was built.
Javascript Regular expressions work well in IE7. In javascript we need a regular
expression that will work in IE7, for a password field that needs to be greater
than or equal to six but less than or equal to twelve characters. Also at least
one special character 0 through 9 or @#$%&+= symbol is required.
1: <script language="javascript" type="text/javascript">
2:
3: function ClientValidate(source, arguments) {
4: arguments.IsValid = false;
5: var htmlString = arguments.Value.toString();
6: var len = htmlString.length;
7: if (len > 5 && len < 13) {
8: arguments.IsValid = true;
9: var regval = /[a-zA-Z]/ // Regular expression at least one alpha character
10: if (htmlString.search(regval) == -1)
11: arguments.IsValid = false;
12: regval = /[0-9@#$%&+=]/ // Regular expression defining a digits and special char
13: if (htmlString.search(regval) == -1)
14: arguments.IsValid = false;
15: }
16: }
17: </script>
Add a CustomValidator and point to your textbox.
1: <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="ASPxTextBox1"
2: ClientValidationFunction="ClientValidate" OnServerValidate="OnServerValidateRegEx"
3: Display="Static" Font-Names="verdana" Font-Size="10pt"
4: ErrorMessage="Password must be between 6 and 12 characters, and contain at least 1 number
5: OR special character ('@, #, $, %, &, +, =' are allowed)!" />
A great practice it to add server side validation as well as client side.
A valid password must be 6-12 characters long and contain at least one number or special character (@, #, $, %, &, +, =).
Enter characters tab out of text box to test.
Download demo