Last active
November 3, 2024 11:54
-
-
Save AsbDaryaee/8498a847b20bffd319841bbf144af627 to your computer and use it in GitHub Desktop.
a simple, framework-agnostic TypeScript form validator
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
type ValidatorFunction = (value: string) => string | null; | |
interface FormField { | |
value: string; | |
validators: ValidatorFunction[]; | |
} | |
type Form = { | |
[key: string]: FormField; | |
}; | |
type ValidationResult = { | |
[key: string]: string | null; | |
}; | |
/** | |
* Runs the validation on a given form and returns validation results. | |
* @param form The form to validate. | |
* @returns A record containing field names and their respective error message or null if valid. | |
*/ | |
function validateForm(form: Form): ValidationResult { | |
const result: ValidationResult = {}; | |
for (const fieldName in form) { | |
const field = form[fieldName]; | |
for (const validator of field.validators) { | |
const error = validator(field.value); | |
if (error) { | |
result[fieldName] = error; | |
break; // Stop at the first validation error per field | |
} else { | |
result[fieldName] = null; | |
} | |
} | |
} | |
return result; | |
} | |
// Example Validators | |
const required: ValidatorFunction = (value) => { | |
return value.trim() ? null : 'This field is required'; | |
}; | |
const minLength = (min: number): ValidatorFunction => { | |
return (value) => value.length >= min ? null : `Minimum length is ${min} characters`; | |
}; | |
const emailFormat: ValidatorFunction = (value) => { | |
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; | |
return emailRegex.test(value) ? null : 'Invalid email format'; | |
}; | |
// Example usage | |
const form: Form = { | |
username: { | |
value: '', | |
validators: [required, minLength(3)], | |
}, | |
email: { | |
value: 'test@example', | |
validators: [required, emailFormat], | |
}, | |
password: { | |
value: '12345', | |
validators: [required, minLength(6)], | |
}, | |
}; | |
const validationResult = validateForm(form); | |
console.log(validationResult); // { username: 'This field is required', email: 'Invalid email format', password: 'Minimum length is 6 characters' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment