, , ,

Regex for UUID in JavaScript, Angular, React, Python with Examples

Learn how to validate UUIDs using regular expressions (regex) in JavaScript, Angular, React, and Python with step-by-step examples and complete code snippets.

By.

•

min read

During software development, while working with crucial data sets, essential to ensure the uniqueness of identifiers in the applications. Universally Unique Identifiers (UUIDs) serve as a popular choice for generating unique identifiers.

In this article, we will explore how to validate UUIDs using regular expressions (regex) in various programming languages and frameworks including JavaScript, Angular, React, and Python.

We will walk through examples and provide complete code snippets to make the process easy to understand and easy to consume in applications.

[lwptoc]

What is UUID?

A UUID is a 128-bit number represented as a string of 32 hexadecimal digits, separated by hyphens into five groups. The general structure is 8-4-4-4-12, totalling 36 characters, which includes the hyphens. For example: 123e4567-e89b-12d3-a456-426614174000.

The various parts of a UUID represent the following:

  1. Time-low (8 digits): The first group of 8 hexadecimal digits represents the low field of the timestamp. It is the least significant 32 bits of the timestamp.
  2. Time-mid (4 digits): The second group of 4 hexadecimal digits represent the mid field of the timestamp. It is the middle 16 bits of the timestamp.
  3. Time-high-and-version (4 digits): The third group of 4 hexadecimal digits represents the high field of the timestamp multiplexed with the version number. It contains the most significant 12 bits of the timestamp and 4 bits for the UUID version.
  4. Clock-seq-and-reserved, Clock-seq-low (4 digits): The fourth group of 4 hexadecimal digits represents the clock sequence. The first 2 digits contain the 2 most significant bits of the clock sequence, and the remaining 2 digits store the least significant bits of the clock sequence.
  5. Node (12 digits): The fifth group of 12 hexadecimal digits represents the node field. It contains a 48-bit value, usually derived from the hardware (MAC) address of the device generating the UUID.

The UUID version defines the internal structure and the method used to generate it. The most common version is version 4, which generates UUIDs using random numbers.

 

Now, let’s explore how to validate UUIDs using regex in JavaScript, Angular, React, and Python.

 

JavaScript

Let’s have a look, at how we can validate a UUID string if its valid or not by using regex expressions:

 

Vanilla JavaScript

function isValidUUID(uuid) {
  const uuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i;
  return uuidRegex.test(uuid);
}

const sampleUUID = '123e4567-e89b-12d3-a456-426614174000';
console.log(isValidUUID(sampleUUID)); // Output: true

 

Node.js

// uuidValidator.js
const fs = require('fs');

function isValidUUID(uuid) {
  const uuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i;
  return uuidRegex.test(uuid);
}

module.exports = isValidUUID;

// app.js
const isValidUUID = require('./uuidValidator');
const sampleUUID = '123e4567-e89b-12d3-a456-426614174000';
console.log(isValidUUID(sampleUUID)); // Output: true

 

Angular

In Angular application, while working with TypeScript we can easily verify by using the class function or a custom validator.

 

Validating in Angular Component

// uuid-validator.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-uuid-validator',
  templateUrl: './uuid-validator.component.html',
  styleUrls: ['./uuid-validator.component.css'],
})
export class UuidValidatorComponent {
  isValidUUID(uuid: string): boolean {
    const uuidRegex =
      /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i;
    return uuidRegex.test(uuid);
  }
}

 

Template HTML

<input [(ngModel)]="sampleUUID" placeholder="Enter UUID">
<button (click)="validationResult = isValidUUID(sampleUUID)">Validate</button>

<p *ngIf="validationResult">Valid UUID</p>
<p *ngIf="validationResult === false">Invalid UUID</p>

 

Using a Custom Validator

// uuid.validator.ts
import { AbstractControl, ValidatorFn } from '@angular/forms';

export function uuidValidator(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const uuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i;
    const valid = uuidRegex.test(control.value);
    return valid ? null : { 'invalidUuid': { value: control.value } };
  };
}

// app.component.ts
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { uuidValidator } from './uuid.validator';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  uuidControl = new FormControl('', [Validators.required, uuidValidator()]);
}

 

React

Let’s have a look how we check UUIDs validation in functional components or as custom validator functions which can be exported to be utilized anywhere.

React Component

import React, { useState } from 'react';

function UuidValidator() {
  const [uuid, setUuid] = useState('');
  const [isValid, setIsValid] = useState(null);

  function isValidUUID(uuid) {
    const uuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i;
    return uuidRegex.test(uuid);
  }

  function handleValidate() {
    setIsValid(isValidUUID(uuid));
  }

  return (
    <div>
      <input
        value={uuid}
        onChange={(e) => setUuid(e.target.value)}
        placeholder="Enter UUID"
      />
      <button onClick={handleValidate}>Validate</button>
      {isValid === true && <p>Valid UUID</p>}
      {isValid === false && <p>Invalid UUID</p>}
    </div>
  );
}

export default UuidValidator;

 

Custom Validator

// uuidValidator.js
export default function uuidValidator(uuid) {
  const uuidRegex =
    /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/i;
  return uuidRegex.test(uuid);
}


// App.js
import React, { useState } from 'react';
import uuidValidator from './uuidValidator';

function App() {
  const [uuid, setUuid] = useState('');
  const [isValid, setIsValid] = useState(null);

  function handleValidate() {
    setIsValid(uuidValidator(uuid));
  }

  return (
    <div>
      <input
        value={uuid}
        onChange={(e) => setUuid(e.target.value)}
        placeholder="Enter UUID"
      />
      <button onClick={handleValidate}>Validate</button>
      {isValid === true && <p>Valid UUID</p>}
      {isValid === false && <p>Invalid UUID</p>}
    </div>
  );
}

export default App;

Python

In Python, we can define a common function inside he script to validate the UUID string:

Python Script

import re

def is_valid_uuid(uuid):
    uuid_regex = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$")
    return bool(uuid_regex.match(uuid))

sample_uuid = "123e4567-e89b-12d3-a456-426614174000"
print(is_valid_uuid(sample_uuid))  # Output: True

Python Function

import re

def is_valid_uuid(uuid):
    uuid_regex = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$")
    return bool(uuid_regex.match(uuid))

def main():
    sample_uuid = "123e4567-e89b-12d3-a456-426614174000"
    print(is_valid_uuid(sample_uuid))  # Output: True

if __name__ == "__main__":
    main()

 

Conclusion

In this article, we have explored the use of regular expressions for UUID validation in JavaScript, Angular, React, and Python. By using the examples provided, you can easily integrate UUID validation into your applications, ensuring the uniqueness of identifiers throughout your projects. Hope this was helpful…

Leave a Reply

Your email address will not be published. Required fields are marked *