I'm using joi-browser
for form validation in React. Problem which I'm facing is to validate password
and confirmPassword
on input.
The schema I'm using is same which is provided in another stackoverflow question.
password: Joi.string().min(3).max(15).required(),
confirmPassword: Joi.any().valid(Joi.ref('password')).required().options({ language: { any: { allowOnly: 'must match password' } } })
Once I start typing in confirmPassword
, my error comes even it is same as password
and on submit it disappear and submit form. but if confirmPassword
is not same it fails to submit that is ok.
What I want is, it should validate on onChange
event, and if confirmPassword
field matches password
field the error must be removed.
Code logic is, all fields are defined in formData
in the state, and all errors will be stored in errors
object with same name in the state.errors
. If error comes, it create entry in errors object else remove it from errors object.
My form state is:
state = {
formData: {
password: '',
confirmPassword: ''
},
errors: {}
}
onChange method is:
onChangeField = ({ currentTarget: input }) => {
const errors = { ...this.state.errors };
const errorMsg = this.validateField(input);
if (errorMsg) errors[input.name] = errorMsg;
else delete errors[input.name];
const formData = { ...this.state.formData };
formData[input.name] = input.value;
this.setState({ formData, errors });
}
validateField = ({ name, value }) => {
const obj = { [name]: value };
const schema = { [name]: this.schema[name] };
const { error } = Joi.validate(obj, schema);
return error ? error.details[0].message : null;
};