Link to home
Start Free TrialLog in
Avatar of Jerry Miller
Jerry MillerFlag for United States of America

asked on

Regular Expression help

I am using this regex in my code to validate the length of the entered data before allowing the user to submit the page.

^[a-zA-Z0-9\-\s]{11,23}

The characters can be alphanumeric, but needs to be either 11 or 23 in length. The example above allows anything between 11 and 23. I have been looking for about an hour for an example to do this, but can't seem to get it right.

Can someone help me adjust this so that my users can only enter 11 or 23 characters?
ASKER CERTIFIED SOLUTION
Avatar of Mazdajai
Mazdajai
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Alternatively:
^[a-zA-Z0-9\-\s]{11}(?:[a-zA-Z0-9\-\s]{12})?$

Open in new window

You mean {23} not {12}?
Avatar of Jerry Miller

ASKER

I had to put the 23 in the first part of the clause, but other than that it is awesome! I didn't know that I could use the pipe (|) command as an OR in regex.

Any idea why it works like below, but no the other way around? Maybe because with the more restrictive clause in the front it doesn't process the second correctly?

^([a-zA-Z0-9\-\s]{23})|([a-zA-Z0-9\-\s]{11})$

Thanks for the quick help.
I don't see a reason why it would not work, do you have a sample output? You can try kaufmed's as well, both should work.
I didn't see kaufmed's reply until I submitted my response or I would have tried it too and split the points.

I am using it to validate user input on a textbox in the markup page to make sure they are following established business rules. I am also validating in the code behind, but I am trying to give them visible feedback as they type so it can be corrected as it is entered.

<asp:RegularExpressionValidator ID="txtEntryNumberRegExpValidator" runat="server" ErrorMessage="Entry Number can contain letters & numbers with a hypen (-): 11 or 23 characters"
        ControlToValidate="txtEntryNumber" ValidationExpression="^([a-zA-Z0-9\-\s]{23})|([a-zA-Z0-9\-\s]{11})$" />
@Mazdajai
You mean {23} not {12}?
No, I mean 12.  11 + 12 = 23    : )