62 lines
1.7 KiB
JavaScript
62 lines
1.7 KiB
JavaScript
|
|
export default class FormValidator {
|
||
|
|
static rules = {
|
||
|
|
required: (value) => {
|
||
|
|
if (!value || (typeof value === 'string' && value.trim() === '')) {
|
||
|
|
return 'This field is required';
|
||
|
|
}
|
||
|
|
return null;
|
||
|
|
},
|
||
|
|
email: (value) => {
|
||
|
|
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||
|
|
return regex.test(value) ? null : 'Invalid email address';
|
||
|
|
},
|
||
|
|
minLength: (min) => (value) => {
|
||
|
|
return (value?.length || 0) >= min ? null : `Minimum ${min} characters required`;
|
||
|
|
},
|
||
|
|
maxLength: (max) => (value) => {
|
||
|
|
return (value?.length || 0) <= max ? null : `Maximum ${max} characters allowed`;
|
||
|
|
},
|
||
|
|
pattern: (regex, message = 'Invalid format') => (value) => {
|
||
|
|
return regex.test(value) ? null : message;
|
||
|
|
},
|
||
|
|
custom: (fn) => (value) => {
|
||
|
|
try {
|
||
|
|
const error = fn(value);
|
||
|
|
return error || null;
|
||
|
|
} catch (err) {
|
||
|
|
return 'Validation error';
|
||
|
|
}
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
static validate(formData, schema) {
|
||
|
|
const errors = {};
|
||
|
|
|
||
|
|
for (const [field, rules] of Object.entries(schema)) {
|
||
|
|
const value = formData[field];
|
||
|
|
|
||
|
|
for (const rule of rules) {
|
||
|
|
let error = null;
|
||
|
|
|
||
|
|
if (typeof rule === 'function') {
|
||
|
|
error = rule(value);
|
||
|
|
}
|
||
|
|
|
||
|
|
if (error) {
|
||
|
|
errors[field] = error;
|
||
|
|
break;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return {
|
||
|
|
isValid: Object.keys(errors).length === 0,
|
||
|
|
errors
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
static createSchema() {
|
||
|
|
return {};
|
||
|
|
}
|
||
|
|
}
|