在 JavaScript 中验证 GUID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24573155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validating a GUID in JavaScript
提问by user3284007
I'm trying to build a regular expression that checks to see if a value is an RFC4122valid GUID. In an attempt to do that, I'm using the following:
我正在尝试构建一个正则表达式,用于检查值是否为RFC4122有效 GUID。为了做到这一点,我正在使用以下内容:
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.
我确信我的 GUID 是有效的 GUID。我以为我抓住了 GUID 的正确正则表达式。但是,无论如何,我总是收到一条错误消息,指出它不是 GUID。
What am I doing wrong?
我究竟做错了什么?
回答by RichieHindle
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:
/
使用 构造正则表达式时,不得在正则表达式中包含字符new RegExp
,并且应该将修饰符i
作为第二个参数传递给构造函数:
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:
但在这种情况下,没有必要使用new RegExp
- 你可以说:
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;
回答by Ja?ck
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:
如果您使用的是RegExp
对象,则不能将修饰符添加为/i
. 您必须将它们作为第二个参数传递给构造函数:
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