@modular-forms/solid
Version:
The modular and type-safe form library for SolidJS
36 lines (35 loc) • 1.42 kB
JavaScript
import { batch, untrack } from 'solid-js';
import { getFieldArrayStore, getFieldStore, updateFormInvalid } from '../utils';
import { focus } from './focus';
/**
* Sets the error of the specified field or field array.
*
* @param form The form of the field.
* @param name The name of the field.
* @param error The error message.
* @param options The error options.
*/
export function setError(form, name, error, { shouldActive = true, shouldTouched = false, shouldDirty = false, shouldFocus = !!error, } = {}) {
batch(() => {
untrack(() => {
for (const fieldOrFieldArray of [
getFieldStore(form, name),
getFieldArrayStore(form, name),
]) {
if (fieldOrFieldArray &&
(!shouldActive || fieldOrFieldArray.active.get()) &&
(!shouldTouched || fieldOrFieldArray.touched.get()) &&
(!shouldDirty || fieldOrFieldArray.dirty.get())) {
// Set error to field or field array
fieldOrFieldArray.error.set(error);
// Focus element if set to "true"
if (error && 'value' in fieldOrFieldArray && shouldFocus) {
focus(form, name);
}
}
}
});
// Update invalid state of form
updateFormInvalid(form, !!error);
});
}