Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating a GUID in JavaScript [duplicate]

I'm trying to build a regular expression that checks to see if a value is an RFC4122 valid GUID. In an attempt to do that, I'm using the following:

var id = '1e601ec7-fb00-4deb-a8bb-d9da5147d878';
var pattern = new RegExp('/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i');
if (pattern.test(id) === true) {
  console.log('We have a winner!');
} else {
  console.log('This is not a valid GUID.');
}

I'm confident that my GUID is a valid GUID. I thought I grabbed the correct regular expression for a GUID. However, no matter what, I always get an error that says its not a GUID.

What am I doing wrong?

like image 424
user3284007 Avatar asked Jul 04 '14 11:07

user3284007


2 Answers

You mustn't include the / characters in the regex when you're constructing it with new RegExp, and you should pass modifiers like i as a second parameter to the constructor:

var pattern = new RegExp('^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', 'i');

But in this case there's no need to use new RegExp - you can just say:

var pattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
like image 91
RichieHindle Avatar answered Oct 08 '22 10:10

RichieHindle


If you're using RegExp object, you can't add the modifiers as /i. You have to pass any them as the second argument to the constructor:

new RegExp('^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$', 'i');

Or use the literal syntax:

/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
like image 43
3 revs, 2 users 90% Avatar answered Oct 08 '22 10:10

3 revs, 2 users 90%