feat: add form field validators

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Luca Oelfke 2026-02-13 13:12:47 +01:00
parent d87b60d98e
commit f7d1b01531

48
src/utils/validators.ts Normal file
View file

@ -0,0 +1,48 @@
import { FormField } from '../types';
export interface ValidationError {
fieldId: string;
message: string;
}
/**
* Validate form values against field definitions.
* Returns an empty array if everything is valid.
*/
export function validateForm(
fields: FormField[],
values: Record<string, unknown>,
): ValidationError[] {
const errors: ValidationError[] = [];
for (const field of fields) {
const value = values[field.id];
if (field.required) {
if (value === undefined || value === null || value === '') {
errors.push({ fieldId: field.id, message: `${field.label} is required.` });
continue;
}
if (Array.isArray(value) && value.length === 0) {
errors.push({ fieldId: field.id, message: `${field.label} is required.` });
continue;
}
}
if (value !== undefined && value !== null && value !== '') {
if (field.type === 'number' && typeof value === 'string') {
if (isNaN(Number(value))) {
errors.push({ fieldId: field.id, message: `${field.label} must be a number.` });
}
}
if (field.type === 'rating') {
const n = Number(value);
if (isNaN(n) || n < 1 || n > 5) {
errors.push({ fieldId: field.id, message: `${field.label} must be between 1 and 5.` });
}
}
}
}
return errors;
}