Validate password for Minimum and Maximum length using Regular Expression in Asp.Net

← PrevNext →

You can use Regular expressions to validate password minimum and maximum length in Asp.Net.

For example, I have a textbox for password. Passwords usually has some standard min. and max. length. However, different websites use different length. The textbox in this example, has a limit of minimum 5 characters and maximum of 15 characters.

I am using Regular Expressions to validate (or check) if the length is Ok. In-addition, it will show a message to the user.

<div>
    Password:
    <asp:TextBox 
        ID="tbPass" 
        runat="server" 
        placeholder="Enter password" 
        Width="300px">
    </asp:TextBox>  (Min. 5 chars and Max. 15 chars)

    <p>
        <asp:RegularExpressionValidator
            runat="server" 
            ID="validate"
            ControlToValidate="tbPass"
            ValidationExpression="^[a-zA-Z0-9'@&#.\s]{5,15}$"
            ErrorMessage="length of the password should be between 5 and 15 characters"
            ForeColor="red">
        </asp:RegularExpressionValidator>
    </p>
</div>

I am using the "RegularExpressionValidator" control, which will check the number of characters entered in the textbox.

It has few properties of which two are important.

ControlToValidate: This property has the textbox "id", which we need to validate.

ValidationExpression: This property has a sequence of characters that specifies a match in the textbox.
The MetaCharacters inside the square box [], checks if the inputs are valid characters like alphabets, numbers or special characters. It is followed by a curly bracket {}, which has two numbers 5 and 15 (for minimum and maximum characters).

Remember: In case you have a submit button on your webpage, and if the RegularExpressionValidator throws an error message, it will not submit the values.

Happy coding. 🙂

← PreviousNext →