Hello Everyone,
I am doing Mastering React Course. In the form section, I am facing problem. I cannot use Joi validation with validateProperty property. handleChange for Joi is not giving result properly.
Joi = 17.6.0 ,
React = 18
import { Component } from "react";
import Joi from "joi";
import Input from "./common/input";
class LoginForm extends Component {
state = {
account: {
username: "",
password: "",
},
errors: {},
};
schema = Joi.object({
username: Joi.string().required(),
password: Joi.string().required(),
});
validateProperty = ({ name, value }) => {
const obj = { [name]: value };
const schema = { [name]: this.schema[name] };
const { error } = this.schema.validate(obj, schema);
return error ? error.details[0].message : null;
};
handleChange = ({ currentTarget: input }) => {
const errors = { ...this.state.errors };
const errorMessage = this.validateProperty(input);
if (errorMessage) errors[input.name] = errorMessage;
else delete errors[input.name];
const account = { ...this.state.account };
account[input.name] = input.value;
this.setState({ account, errors });
};
validate = () => {
const { username, password } = this.state.account;
const options = { abortEarly: false };
const { error } = this.schema.validate({ username, password }, options);
if (!error) return null;
const errors = {};
for (let item of error.details) {
errors[item.path[0]] = item.message;
}
return errors;
};
handleSubmit = (e) => {
e.preventDefault();
const errors = this.validate();
this.setState({ errors: errors || {} });
if (errors) return;
console.log(this.state.account);
// Call the server
};
render() {
const { account, errors } = this.state;
return (
<>
<form onSubmit={this.handleSubmit}>
<Input
name="username"
label="Username"
value={account.username}
onChange={this.handleChange}
error={errors.username}
/>
<Input
name="password"
label="Password"
value={account.password}
onChange={this.handleChange}
error={errors.password}
/>
<button type="submit" className="btn btn-primary mt-3">
Submit
</button>
</form>
</>
);
}
}
export default LoginForm;
Please help me why my validateProperty not working.