📘
Form Validation System 📝
Advanced
170 XP
70 min
Lesson Content
Form Validation System 📝
Create a robust form validation system with TypeScript. Learn advanced types and validation patterns!
Validation Types
type ValidationRule = (value: T) => string | null;
type ValidationResult = {
isValid: boolean;
errors: string[];
};
interface FormData {
email: string;
password: string;
age: number;
}
function validateEmail(email: string): string | null {
return email.includes('@') ? null : 'Invalid email';
} Example Code
Create typed validation system
type ValidationResult = {
isValid: boolean;
errors: string[];
};
function validateEmail(email: string): string | null {
if (!email.includes('@')) return 'Invalid email';
if (email.length < 5) return 'Email too short';
return null;
}
function validateForm(email: string): ValidationResult {
const errors: string[] = [];
const emailError = validateEmail(email);
if (emailError) errors.push(emailError);
return {
isValid: errors.length === 0,
errors
};
}
console.log(validateForm('test@example.com'));
console.log(validateForm('invalid'));Expected Output:
Validation results for different inputs
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code