• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 95
  • Last Modified:

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";
0
badtz7229
Asked:
badtz7229
  • 4
  • 4
  • 2
1 Solution
 
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
 
Lee SavidgeCommented:
I haven't tested but maybe this:

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

Open in new window

0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
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
 
Alexandre SimõesManager / 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
 
badtz7229Author Commented:
thank you. this worked for  me.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

  • 4
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now