rune-form
Version:
Type-safe reactive form builder for Svelte 5
85 lines (84 loc) • 3.21 kB
JavaScript
/**
* Creates a custom validator from validation functions
*/
export function createCustomValidator(validator) {
return {
parse(data) {
return data;
},
safeParse(data) {
const errors = {};
let hasErrors = false;
// Run all validation functions
for (const [key, validateFn] of Object.entries(validator)) {
if (validateFn && typeof validateFn === 'function') {
const value = data[key];
try {
const result = validateFn(value, data);
// Handle both sync and async results
if (result instanceof Promise) {
// For sync safeParse, we'll treat async validators as valid
// The async version will handle these properly
continue;
}
if (Array.isArray(result) && result.length > 0) {
errors[key] = result;
hasErrors = true;
}
}
catch {
errors[key] = ['Validation error occurred'];
hasErrors = true;
}
}
}
if (hasErrors) {
return { success: false, errors };
}
return { success: true, data: data };
},
async safeParseAsync(data) {
const errors = {};
let hasErrors = false;
// Run all validation functions (including async ones)
for (const [key, validateFn] of Object.entries(validator)) {
if (validateFn && typeof validateFn === 'function') {
const value = data[key];
try {
const result = validateFn(value, data);
let validationErrors;
if (result instanceof Promise) {
validationErrors = await result;
}
else {
validationErrors = result;
}
if (Array.isArray(validationErrors) && validationErrors.length > 0) {
errors[key] = validationErrors;
hasErrors = true;
}
}
catch {
errors[key] = ['Validation error occurred'];
hasErrors = true;
}
}
}
if (hasErrors) {
return { success: false, errors };
}
return { success: true, data: data };
},
resolveDefaults(data) {
return data;
},
getPaths() {
return Object.keys(validator);
},
getInputAttributes() {
// Return empty object for custom validators
// You could enhance this to return specific attributes if needed
return {};
}
};
}