0

I want a regex pattern allowing only alphanumeric value, neither only alphabets nor digits, having minimum length = 4 and maximum length = 15,

I tried using /^[a-zA-Z0-9]{4,15}$/ , but this pattern also allows only alphabets and only digits.

Please help me out

2
  • The regex pattern you mention should allow alphabets OR digits. Commented May 29, 2013 at 8:46
  • @SiddharthaRT that's the problem he only want to get mixed results Commented May 29, 2013 at 8:48

3 Answers 3

2

This should do the trick:

^(?=^.{4,15}$)([a-zA-Z]+[0-9][a-zA-Z0-9]*|[0-9]+[a-zA-Z][a-zA-Z0-9]*)$

See working example here: http://regexr.com?351ia

Explanation: (Updated: now with length check)

First the positive lookahead (?=^.{4,15}$) checks the length of your string.

If your string starts with a letter this part of the regex is used to evaluate it:

[a-zA-Z]+[0-9][a-zA-Z0-9]*

  • [a-zA-Z]+ means that the string starts with at least one letter
  • [0-9] then at some point there must be a number
  • [a-zA-Z0-9]* followed by any amount of numbers or letters

If your string starts with a number the second part of the regex is used:

[0-9]+[a-zA-Z][a-zA-Z0-9]*

Same as the above, only this time there must be a letter somewhere in the string.

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

1 Comment

You did not check for the length constraints.
0

You may want to do a double lookahead to look for numbers and letters, once numbers and letters are found, the match will continue, else it won't.

Regex: /^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9]{4,15}$/

Comments

0

Use your original for the alphanumeric and length tests, then verify that the string contains alpha and numeric by testing for a digit followed by an alpha or vice-versa anywhere in the string.

   /^[a-z\d]{4,15}$/i.test (s) && /\d[a-z]|[a-z]\d/i.test (s);

Comments

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.