Last active
August 4, 2025 02:52
-
-
Save leonardof02/c44ddb921f45e3370ee499b3962ae6b1 to your computer and use it in GitHub Desktop.
Best practices validation in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export interface ValidationError extends Error { | |
| errors: string[]; | |
| } | |
| // Example: Password validator | |
| export function validatePassword(password: string) { | |
| const sixMinimumChars = /^.{6,}$/; | |
| const atLeastOneLowercase = /^(?=.*[a-z]).*$/; | |
| const atLeastOneUppercase = /^(?=.*[A-Z]).*$/; | |
| const atLeastOneDigit = /^(?=.*\d).*$/; | |
| const nonAlphanumericalChar = /^(?=.*\W).*$/; | |
| const errorMessage = "The password must contain at least "; | |
| const errors: string[] = []; | |
| if (!sixMinimumChars.test(password)) errors.push(`${errorMessage} 6 characters`); | |
| if (!atLeastOneLowercase.test(password)) errors.push(`${errorMessage} 1 lowercase character`); | |
| if (!atLeastOneUppercase.test(password)) errors.push(`${errorMessage} 1 uppercase character`); | |
| if (!atLeastOneDigit.test(password)) errors.push(`${errorMessage} 1 numerical digit`); | |
| if (!nonAlphanumericalChar.test(password)) errors.push(`${errorMessage} 1 or more spaces`); | |
| if (errors.length > 0) { | |
| const validationError = new Error("Validation errors") as ValidationError; | |
| validationError.errors = errors; | |
| throw validationError; | |
| } | |
| } | |
| // Handle Validation Exceptions | |
| function getPasswordErrors(password: string) { | |
| try { | |
| validatePassword(password); | |
| } catch (error: any) { | |
| const errors = (error as ValidationError).errors; | |
| // ... Procesing errors | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment