Skip to content

Instantly share code, notes, and snippets.

@leonardof02
Last active August 4, 2025 02:52
Show Gist options
  • Select an option

  • Save leonardof02/c44ddb921f45e3370ee499b3962ae6b1 to your computer and use it in GitHub Desktop.

Select an option

Save leonardof02/c44ddb921f45e3370ee499b3962ae6b1 to your computer and use it in GitHub Desktop.
Best practices validation in React
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