MOCKSTACKS
EN
Questions And Answers

More Tutorials




How to validate GUID from a string in Javascript?


Given string str, the task is to check whether the given string is valid GUID (Globally Unique Identifier) or not by using Regular Expression.

The valid GUID (Globally Unique Identifier) must specify the following conditions:

1. It should be a 128-bit number.
2. It should be 36 characters (32 hexadecimal characters and 4 hyphens) long.
3. It should be displayed in five groups separated by hyphens (-).
4. Microsoft GUIDs are sometimes represented with surrounding braces.

Examples:

Input: str = “123e4567-e89b-12d3-a456-9AC7CBDCEE52” 
Output: true 
Explanation: 
The given string satisfies all the above mentioned conditions. Therefore, it is a valid GUID (Globally Unique Identifier).
Input: str = “123e4567-h89b-12d3-a456-9AC7CBDCEE52” 
Output: false 
Explanation: 
The given string contains ‘h’, the valid hexadecimal characters should be followed by character from a-f, A-F, and 0-9. Therefore, it is not a valid GUID (Globally Unique Identifier).
Input: str = “123e4567-h89b-12d3-a456” 
Output: false 
Explanation: 
The given string has 20 characters. Therefore, it is not a valid GUID (Globally Unique Identifier). 

Approach:
The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer:

1. Get the String.
2. Create a regular expression to check valid GUID (Globally Unique Identifier) as mentioned below:

regex =^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$


Conclusion

In this page (written and validated by ) you learned about . What's Next? If you are interested in completing Javascript tutorial, we encourage you simply to start here: Javascript Tutorial.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.