Hello coders,
I have been taking React lessons with codewithmosh.com in the last few weeks.
Until the topic ‘Forms - Validating a Form Using Joi’ I am facing with this problem when I want to enter my username (or password) in the field.
I have followed one by one the code shown by Mosh in the tutorial but I am the only one who has the problem.
Anyone help?
Thank you.
(loginForm.jsx)
import React, { Component } from “react”;
import Input from “./input”;
import Joi from “joi-browser”;
class LoginForm extends Component {
state = {
account: { username: "", password: "" },
errors: {},
};
schema = {
username: Joi.string().required().label("Username"),
password: Joi.string().required().label("Password"),
};
validate = () => {
const options = { abortEarly: false };
const result = Joi.validate(this.state.account, this.schema, options);
if (!result.error) return null;
const errors = {};
for (let item of result.error.details) {
errors[item.path[0]] = item.message;
}
return errors;
};
validateProperty = ({ name, value }) => {
const obj = { [name]: value };
const schema = { [name]: this.schema[name] };
const { error } = Joi.validate(obj, schema);
return error ? null : error.details[0].message;
// if (name === "username") {
// if (value.trim() === "") return "Username is required.";
// }
// if (name === "password") {
// if (value.trim() === "") return "Password is required.";
// }
};
handleSubmit = (e) => {
e.preventDefault();
const errors = this.validate();
this.setState({ errors: errors || {} });
if (errors) return;
};
handleChange = (e) => {
const cloneErrors = { ...this.state.errors };
const errorMessage = this.validateProperty(e);
if (errorMessage) {
cloneErrors[e.name] = errorMessage;
} else {
delete cloneErrors[e.name];
}
const account = { ...this.state.account };
account[e.currentTarget.name] = e.currentTarget.value;
this.setState({ account, errors: cloneErrors });
};
render() {
return (
<div>
<h1>Login</h1>
<form onSubmit={this.handleSubmit}>
<Input
name="username"
value={this.state.account.username}
label="Username"
onChange={this.handleChange}
error={this.state.errors.username}
/>
<Input
name="password"
value={this.state.account.password}
label="Password"
onChange={this.handleChange}
error={this.state.errors.password}
/>
<button className="btn btn-primary">Login</button>
</form>
</div>
);
}
}
export default LoginForm;
(input.jsx)
import React from “react”;
const Input = (props) => {
return (
<div className="form-group">
<label htmlFor={props.name}>{props.label}</label>
<input
autoFocus
value={props.value}
onChange={props.onChange}
type="text"
className="form-control"
id={props.name}
name={props.name}
/>
{props.error && <div className="alert alert-danger">{props.error}</div>}
</div>
);
};
export default Input;
p / s: Sorry for my English.