Stackbits is going through a refresh! Some features may not be available. Follow @stackbitss on twitter for updates.
Utilities > Regex Validations

Regex Validations

Regular expressions are powerful tools for validating input formats efficiently. This section provides a collection of commonly used regex patterns and utility functions to ensure data integrity and prevent incorrect user inputs.

1. Email Validation

const validateEmail = (email: string): boolean => { const regex = /^[w-.]+@([w-]+.)+[w-]{2,4}$/; return regex.test(email); }

2. Mobile Number Validation

// * Number should be atleast 7 digits long and shorter than 16 digit s const validateMobileNumber = (mobile: string): boolean => { const regex = /^+?[1-9]d{6,14}$/; return regex.test(mobile); }

3. Password Validation

// * Password should be atleast 6 characters long and // * should contain atleast one uppercase letter, one // * lowercase letter and one special character const validatePassword = (password: string): boolean => { const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*W).{6,}$/; return regex.test(password); }

4. URL Validation

const validateURL = (url: string): boolean => { const regex = /^(https?://)?([w.-]+).([a-z]{2,6})([/w .-]*)*/?$/i; return regex.test(url); }

5. Postal Code Validation

const validatePinCode = (pin: string): boolean => { const regex = /^d{6}$/; // Supports 6 digit PIN codes return regex.test(pin); }

6. Credit Card Validation

// * Credit Card number should contain 16 digits // * Number can be in the following formats: // * XXXX-XXXX-XXXX-XXXX or XXXXXXXXXXXXXXXX or XXXX XXXX XXXX XXXX const validateCreditCard = (cardNumber: string): boolean => { const regex = /^(d{4}[- ]?){3}d{4}|d{16}$/; return regex.test(cardNumber); }