Examples
Base
import { createForm } from 'effector-final-form';
const form = createForm<{ login: string; password: string }>({
onSubmit: console.log,
subscribeOn: ['submitSucceeded', 'submitting'],
});
const loginField = form.api.registerField({
name: 'login',
subscribeOn: ['value', 'error', 'validating'],
validate: (x) => (x?.length >= 3 ? undefined : 'Incorrect login'),
});
loginField.$.watch(console.log);
// {value: undefined, error: undefined, validating: true}
// {name: "login", error: "Incorrect login", value: undefined, validating: false}
const passwordField = form.api.registerField({
name: 'password',
subscribeOn: ['value', 'error', 'validating'],
validate: (x) => (x?.length >= 3 ? undefined : 'Incorrect password'),
});
passwordField.$.watch(console.log);
// {value: undefined, error: undefined, validating: true}
// {name: "password", error: "Incorrect password", value: undefined, validating: false}
loginField.api.changeFx('John');
// {name: "login", error: undefined, value: "John", validating: true}
// {name: "login", error: undefined, value: "John", validating: false}
passwordField.api.changeFx('secret');
// {name: "password", error: undefined, value: "secret", validating: true}
// {name: "password", error: undefined, value: "secret", validating: false}
form.api.submitFx();
// {login: "John", password: "secret"}
With dynamic validation
const changeError = createEvent<string>();
const $error = createStore<string>('error');
const validationFx = attach({
effect: createEffect(({ value, errorText }) => {
if (!value || value === '') {
return { firstName: errorText };
}
}),
source: $error,
mapParams: (value, errorText) => ({ value, errorText }),
});
sample({ clock: changeError, target: $error });
const form = createForm<{ firstName: string; lastName: string }>({
onSubmit: () => {},
subscribeOn: ['errors'],
});
const firstNameField = form.api.registerField({ name: 'firstName', subscribeOn: ['error'] });
const lastNameField = form.api.registerField({ name: 'lastName', subscribeOn: ['error'] });
sample({ clock: changeError, target: api.reValidateFx });
firstNameField.api.setValidationFn(validationFx);
// form.$.errors = { firstName: 'error' }
// firstName.error = 'error'
// lastName.error = undefined
changeError('Can not be empty');
// form.$.errors = { firstName: 'Can not be empty' }
// firstName.error = 'Can not be empty'
// lastName.error = undefined