Stackbits
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

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

2. Mobile Number Validation

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

3. Password Validation

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

4. URL Validation

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

5. Postal Code Validation

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

6. Credit Card Validation

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

⭐️ Got a question or feedback?
Feel free to reach out!