import Joi from “joi-browser”;
import Form from “./common/form”;
export default class LoginForm extends Form {
state = {
data: { username: "", password: "" },
errors: {},
};
schema = {
username: Joi.string().required().label("Username"),
password: Joi.string().required().label("Password"),
};
doSubmit = () => {
// call the server
console.log("Form Submitted");
};
render() {
return (
<div>
<h1>Login</h1>
<form onSubmit={this.handleSubmit}>
{this.renderInput("username", "Username")}
{this.renderInput("password", "Password", "password")}
{this.renderButton("Login")}
</form>
</div>
);
}
}
Form.jsx
import React, { Component } from “react”;
import { Joi } from “joi-browser”;
import Input from “./input”;
export default class Form extends Component {
state = {
data: {},
errors: {},
};
validate = () => {
const options = {
abortEarly: false,
};
const { error } = Joi.validate(this.state.data, this.schema, options);
if (!error) return null;
const errors = {};
for (let item of error.details) errors[item.path[0]] = item.message;
return errors;
/* const errors = {};
const { data } = this.state;
if (data.username.trim() === "")
errors.username = "Username is required";
if (data.password.trim() === "")
errors.password = "Password is required";
return Object.keys(errors).length === 0 ? null : errors;
*/
};
validateProperty = ({ 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;
};
handleSubmit = (e) => {
e.preventDefault();
const errors = this.validate();
this.setState({ errors: errors || {} });
if (errors) return;
this.doSubmit();
};
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 data = { ...this.state.data };
data[input.name] = input.value;
// data[e.currentTarget.name] = e.currentTarget.value;
this.setState({ data, errors });
//handle single input
/*
const data = { ...this.state.data };
data.username = e.currentTarget.value;
this.setState({ data });
*/
};
renderButton(label) {
return (
<button disabled={this.validate()} className="btn btn-primary">
{label}
</button>
);
}
renderInput(name, label, type = “text”) {
const { data, errors } = this.state;
return (
<Input
type={type}
name={name}
value={data[name]}
label={label}
onChange={this.handleChange}
error={errors[name]}
/>
);
}
}
“Cannot read property ‘validate’ of undefined”? Anyone can help in finding the error.