Custom Validation Rules
You'll learn how to implement business-specific validation logic that goes beyond basic file checks to enforce contextual requirements like format restrictions per use case or aspect ratio constraints.
Why Custom Rules Matter
While generic validation checks file size and type, real applications often need domain-specific rules. A profile picture might require a square aspect ratio, while a banner image needs 16:9. An invoice upload system might only accept PDFs in production but allow CSVs for testing. These business requirements demand custom validation logic.
Building Custom Validators
Custom validation rules are functions that encapsulate specific business logic:
// Rule: Only square images for avatars
function validateSquareImage(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
const isSquare = img.width === img.height;
isSquare
? resolve({ valid: true })
: reject({ valid: false, error: 'Avatar must be square' });
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
});
}
// Context-specific format rule
function validateByContext(file, context) {
const rules = {
invoice: ['application/pdf'],
report: ['text/csv', 'application/vnd.ms-excel']
};
const allowed = rules[context];
if (!allowed.includes(file.type)) {
return { valid: false, error: `${context} requires: ${allowed.join(', ')}` };
}
return { valid: true };
}
Think of custom validators as specialized inspectors: one checks if boxes are perfectly cubic, another verifies which warehouse a package belongs in.
Key Takeaway: Custom validation rules let you enforce business-specific constraints by wrapping domain logic into reusable validation functions that check file properties against your application's unique requirements.