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
1const validateEmail = (email: string): boolean => {2const regex = /^[w-.]+@([w-]+.)+[w-]{2,4}$/;3return regex.test(email);4}
2. Mobile Number Validation
1// * Number should be atleast 7 digits long and shorter than 16 digit s2const validateMobileNumber = (mobile: string): boolean => {3const regex = /^+?[1-9]d{6,14}$/;4return regex.test(mobile);5}
3. Password Validation
1// * Password should be atleast 6 characters long and2// * should contain atleast one uppercase letter, one3// * lowercase letter and one special character4const validatePassword = (password: string): boolean => {5const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*W).{6,}$/;6return regex.test(password);7}
4. URL Validation
1const validateURL = (url: string): boolean => {2const regex = /^(https?://)?([w.-]+).([a-z]{2,6})([/w .-]*)*/?$/i;3return regex.test(url);4}
5. Postal Code Validation
1const validatePinCode = (pin: string): boolean => {2const regex = /^d{6}$/; // Supports 6 digit PIN codes3return regex.test(pin);4}
6. Credit Card Validation
1// * Credit Card number should contain 16 digits2// * Number can be in the following formats:3// * XXXX-XXXX-XXXX-XXXX or XXXXXXXXXXXXXXXX or XXXX XXXX XXXX XXXX4const validateCreditCard = (cardNumber: string): boolean => {5const regex = /^(d{4}[- ]?){3}d{4}|d{16}$/;6return regex.test(cardNumber);7}
⭐️ Got a question or feedback?
Feel free to reach out!