Pisząc walidację formularza w final form react, nie wiem jak połączyć ze sobą 2 rodzaje dodania funkcji do sprawdzenia walidacji. W polu Field dodając walidację mogę ją sprawdzić tylko dla wartości tego pola. Potrzebuję jednak funkcji do sprawdzenia czy hasło i jego potwierdzenie jest takie samo. Dodając taką funkcję w polu Form w atrybucie validate ona zwyczajnie nie działa..
const required = value => (value ? undefined : 'To pole jest wymagane!')
const mustBeNumber = value => (isNaN(value) ? 'Wartość nie jest liczbą!' : undefined)
const minValue = value =>
isNaN(value) || value >= 0 ? undefined : `Wartość nie może być ujemna!`
const emailReg = value => (value.match(/^[a-z\d]+[\w\d.-]*@(?:[a-z\d]+[a-z\d-]+\.){1,5}[a-z]{2,6}$/) ? undefined : `Niewłaściwy adres e-mail`);
const composeValidators = (...validators) => value =>
validators.reduce((error, validator) => error || validator(value), undefined)
return (
<React.Fragment>
<Form
onSubmit={this.onSubmit}
render={({ handleSubmit, form, submitting, pristine, values }) => (
<form onSubmit={handleSubmit}
validate={values => {
const errors = {}
if (values.confirm !== values.password) {
errors.confirm = 'Hasła różnią się!';
}
return errors;
}}>
<Field name="email"
validate={composeValidators(required, emailReg)} >
{({ input, meta }) => (
<div>
<label>E-mail:</label>
<input
{...input}
type="email"
placeholder="E-mail"
className={styles.pole} />
{meta.error && meta.touched && <span>{meta.error}</span>}
</div>
)}
</Field>
<Field name="password"
validate={required} >
{({ input, meta }) => (
<div>
<label>Hasło:</label>
<input
{...input}
type="password"
placeholder="Hasło" />
{meta.error && meta.touched && <span>{meta.error}</span>}
</div>
)}
</Field>
<Field name="confirm"
validate={required} >
{({ input, meta }) => (
<div>
<label>Powtórz hasło:</label>
<input
{...input}
type="password"
placeholder="Powtórz hasło" />
{meta.error && meta.touched && <span>{meta.error}</span>}
</div>
)}
</Field>