0

I use the following regex to validate a text box's content:

^[A-Za-z.]*[A-Za-z][-A-Za-z0-9,/()&:. ]*$

I would like to validate the length of my text-box in this regexp.

7
  • 4
    This doesn't make sense. Use the maxlength property. Commented Jul 23, 2013 at 9:32
  • i want to give size only 1-128 with this regexp. Commented Jul 23, 2013 at 9:37
  • 1
    By "text-box", do you mean textarea (multi-line) or text input (single line)? On a text input, use the maxlength attribute. On textarea, you have to manually check the value length. Commented Jul 23, 2013 at 9:38
  • Why a regular expression? Why not simply compare the length of the string? Commented Jul 23, 2013 at 9:40
  • i mean by text-area (like text-box for name validation who can take only min-1 and max-128 character). but i want to handle it using regexp Commented Jul 23, 2013 at 9:40

1 Answer 1

1

To check a string's length and format with a regex, you can use numbered repeaters:

^[a-z]{1,128}$

However, if you have a succession of unkown numbers of character classes, you can use zero-length positive lookeahead at the beginning of the regex:

^(?=.{1,128}$)[a-z]*[a-z0-9]*$

So for your regex:

^(?=.{1,128}$)[A-Za-z.]*[A-Za-z][-A-Za-z0-9,/()&:. ]*$

If you can though, I'd still suggest checking myString.length instead.

Sign up to request clarification or add additional context in comments.

4 Comments

That is some of the ugliest, most unnecessary regex I've ever seen... And I'm almost certain it won't do the intended job properly. It could match: ".....a ,", but would fail to match "(test)" or "123".
According to his regex, he doesn't want to match those…
I know. My point is that the original question was clearly misleading, in that you've been asked to solve the incorrect problem in an incorrect way.
Okay, I assumed that the comment being on my answer, you were criticizing the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.