javascript: using RegExp to validate alphanumeric and length of characters

How can i use regexp to validate whether a string is alphanumeric and of 5 characters in length?


i was doing the following

var regexp= /[^A-Za-z0-9]+/;
if ( ! regexp.test(strLocation) )
      throw "Only alpha-numeric characters are permitted";
badtz7229Asked:
Who is Participating?
 
Alexandre SimõesConnect With a Mentor Manager / Technology SpecialistCommented:
Just add a space to the end of that sequence:
var regexp = /^[a-z0-9 ]{5}$/i;

Open in new window

Keep it like this. As it has the i at the end, this regex is case insensitive, no need for the uppercase letters.
0
 
Alexandre SimõesManager / Technology SpecialistCommented:
Like this:
var regexp= /^[A-Za-z0-9]{5}$/;

Open in new window

0
 
Alexandre SimõesManager / Technology SpecialistCommented:
Actually a shorter version would be:
var regexp= /^[a-z0-9]{5}$/i;

Open in new window

0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
Lee SavidgeCommented:
I haven't tested but maybe this:

^([a-zA-Z0-9]){1,5}$

Open in new window

0
 
Lee SavidgeCommented:
Oh ok, 5 chars, then {5} instead of {1,5}
0
 
badtz7229Author Commented:
and i tested as:

var strLocation = SERV**123
var regexp =    /^[A-Za-z0-9]{5}$/i;
if ( regexp.test(strLocation) )
      throw "Only alpha-numeric characters are permitted";
                  
                  
but no error was thrown.

if i use      var regexp =      /[^A-Za-z0-9]+/;                  then indeed an error is thrown.
0
 
badtz7229Author Commented:
oh, i hadn't realized. i forgot to put the "!" in the if statement.
0
 
Alexandre SimõesManager / Technology SpecialistCommented:
yep :)
0
 
badtz7229Author Commented:
how do i permit spaces as a character  as well in this reg expression?
0
 
badtz7229Author Commented:
thank you. this worked for  me.
0
All Courses

From novice to tech pro — start learning today.