Tom
Tom

Reputation: 12998

Adding total character limit to regexp

I have the following regular expression which works fine, but I need to add an over all limit to the number of characters so it can not be more than 50 long

^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$

Any ideas? I tried adding {1,50} in various places but none that worked!

I know email addresses can be more than 50 characters but for reasons I won't go in to, I need to limit it.

Upvotes: 1

Views: 439

Answers (3)

keeganwatkins
keeganwatkins

Reputation: 3686

If you need to know if the string is less than 50 characters, you can check it's length property before doing the regexp. Something like this should work:

if ( emailString.length <= 50 ) {
    // The string is an acceptable length, apply regexp check
} else {
    // The string is too long, no need to check via regexp
}

Of course, you can also add the length constraints to the regexp, but it is may be easier to think of length and format as to separate types of validation. Hope that helps. Cheers!

Upvotes: 0

David L
David L

Reputation: 33873

You probably should not add this to your regex, since it already seems to be quite complex. Rather, perhaps you should think about capturing the string length BEFORE evaluating and returning whatever you need for your pass/fail criteria.

var inp = document.getElementById('myinput');
inp.onkeyup = function() {
  alert(inp.value.length);
}​

Alernatively, you could simply limit the input field length in the HTML

<input type="text" id="Textbox" name="Textbox" maxlength="50" />

Upvotes: 1

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41767

You can wrap the body of your regex in a non capturing group and place the 50 character limit there:

^(?:([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)){1, 50}$

Upvotes: 0

Related Questions