Validation To Check Length Of String Using Regular Expression

Published on
-
1 min read

I came across a problem today when trying to find an effective way to validate the length of a password field within a registration form I was creating. ASP.NET already has a bunch of useful validation controls. Most of which I have already have in use within my registration form, such as the RequiredFieldValidator, CompareValidator and RangeValidator.

Now you might be thinking. What’s your problem dude? Its not hard to validate the length of a field. Yeah, you are right. But all the validation controls I am using (above) do not create post backs. I could have easily created a CustomValidator control to solve my problem, but this only fires once a post back has occurred.

I guess my only solution is to use a RegularExpressionVaildator which meant I had to do some research into RegEx. To use RegEx to validate the length of a string between 0 and y (some number), use the following expression:

.{0,y}

To validate the exact length, use the following expression:

.{y}

Both example’s above will accept any type of characters entered in the field.

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself.