31

I need regex for validating alphanumeric String with length of 3-5 chars. I tried following regex found from the web, but it didn't even catch alphanumerics correctly.

var myRegxp = /^([a-zA-Z0-9_-]+)$/;
if(myRegxp.test(value) == false)
{
    return false;
}
newbie
  • 24,286
  • 80
  • 201
  • 301
  • 2
    Consider learning to read regexes so you can figure out which satisfy your needs and which don't. Or better yet, so you can write your own. – BoltClock Jan 20 '11 at 09:01
  • 1
    That is good idea, but i don't have time for this task to do that, but of course that's what i'll have to do. – newbie Jan 20 '11 at 09:33

3 Answers3

88

add {3,5} to your expression which means length between 3 to 5

/^([a-zA-Z0-9_-]){3,5}$/
Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103
6

You'd have to define alphanumerics exactly, but

/^(\w{3,5})$/ 

Should match any digit/character/_ combination of length 3-5.

If you also need the dash, make sure to escape it (\-) add it, like this: :

/^([\w\-]{3,5})$/ 

Also: the ^ anchor means that the sequence has to start at the beginning of the line (character string), and the $ that it ends at the end of the line (character string). So your value string mustn't contain anything else, or it won't match.

Daniel Gehriger
  • 7,339
  • 2
  • 34
  • 55
4

First this script test the strings N having chars from 3 to 5.

For multi language (arabic, Ukrainian) you Must use this

var regex = /^([a-zA-Z0-9_-\u0600-\u065f\u066a-\u06EF\u06fa-\u06ff\ufb8a\u067e\u0686\u06af\u0750-\u077f\ufb50-\ufbc1\ufbd3-\ufd3f\ufd50-\ufd8f\ufd92-\ufdc7\ufe70-\ufefc\uFDF0-\uFDFD]+){3,5}$/;  regex.test('мшефн');

Other wise the below is for English Alphannumeric only

/^([a-zA-Z0-9_-]){3,5}$/

P.S the above dose not accept special characters

one final thing the above dose not take space as test it will fail if there is space if you want space then add after the 0-9\s

\s

And if you want to check lenght of all string add dot .

var regex = /^([a-zA-Z0-9\s@,!=%$#&_-\u0600-\u065f\u066a-\u06EF\u06fa-\u06ff\ufb8a\u067e\u0686\u06af\u0750-\u077f\ufb50-\ufbc1\ufbd3-\ufd3f\ufd50-\ufd8f\ufd92-\ufdc7\ufe70-\ufefc\uFDF0-\uFDFD]).{1,30}$/;
shareef
  • 9,255
  • 13
  • 58
  • 89