'Error in React Component - Failed to validate the users registration
In the User Registration Code when i try to register a new user. even after entering the same password. I keep getting the "Passwords do not match" error message. I fail to understand where I am going wrong.
I request you to help understand where I am going wrong. Thanks for your help.
I have been trying to fix this for the last couple of days. however I have not been able to find a solution.
This is the code for the User Registration Component code:
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
// react-bootstrap components
import { Button, Card, Container, Row, Col, Form, FloatingLabel, Alert } from "react-bootstrap";
require("dotenv").config();
const api = `${process.env.REACT_APP_API_HOST}/api/register`;
function UserRegistration() {
const [user, setUser] = useState({
email: "",
password: "",
passwordConfirmation: "",
});
const [isSubmittedSignup, setIsSubmittedSignup] = useState(false);
const [errors, setErrors] = useState({});
const [fadeProp, setFadeProp] = useState({ fade: "" });
const [successAlert, setSuccessAlert] = useState("show-success");
const [errorAlert, setErrorAlert] = useState("show-error");
useEffect(() => {
const timeout = setInterval(() => {
if (fadeProp.fade === "fade-in") {
setFadeProp({ fade: "fade-out" });
}
if (successAlert === "show-success") {
setSuccessAlert("hide-success");
}
if (errorAlert === "show-error") {
setErrorAlert("hide-error");
}
}, 3000);
return () => clearInterval(timeout);
}, [fadeProp, successAlert, errorAlert]);
const handleChangeEmail = (event) => {
setUser({
...user,
email: event.target.value,
});
if (user.email) {
errors.email = "";
setErrors(errors);
}
};
const handleChangePassword = (event) => {
setUser({
...user,
password: event.target.value,
});
if (user.password) {
errors.password = "";
setErrors(errors);
}
};
const handleChangePasswordConfirmation = (event) => {
setUser({
...user,
passwordConfirmation: event.target.value,
});
if (user.passwordConfirmation) {
errors.passwordConfirmation = "";
setErrors(errors);
}
if (user.passwordConfirmation === user.password) {
errors.confirm_password = "";
setErrors(errors);
}
};
const validate = () => {
const validateErrors = {};
let isValid = true;
if (!user.email) {
isValid = false;
validateErrors.email = "Please enter a valid email";
}
if (!user.password) {
isValid = false;
validateErrors.password = "Please enter a valid password";
} else if (user.password.length < 8) {
isValid = false;
validateErrors.password = "Password must be min 8 characters";
}
if (!user.passwordConfirmation) {
isValid = false;
validateErrors.passwordConfirmation = "Please confirm password";
} else if (user.passwordConfirmation.length < 8) {
isValid = false;
validateErrors.passwordConfirmation = "Password must be min 8 characters";
}
if (user.password !== user.passwordConfirmation) {
isValid = false;
validateErrors.confirm_password = "Passwords does not match.";
} else {
validateErrors.confirm_password = "";
}
setErrors(validateErrors);
return isValid;
};
const handleSubmitSignup = (event) => {
const handleErrors = {};
event.preventDefault();
const userData = `email=${user.email}&password=${user.password}&
passwordConfirmation=${user.passwordConfirmation}`;
if (validate()) {
axios
.post(api, userData, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
.then((res) => {
if (res.data.succes) {
setIsSubmittedSignup(true);
setErrorAlert("hide-error");
setSuccessAlert("show-success");
setFadeProp({ fade: "fade-in" });
}
})
.catch((error) => {
if (error.response.data.message) {
handleErrors.msgSignup = error.response.data.message;
setErrors(handleErrors);
setIsSubmittedSignup(false);
setSuccessAlert("hide-success");
setErrorAlert("show-error");
setFadeProp({ fade: "fade-in" });
}
});
}
};
return (
<Container fluid>
<Row>
<Col />
<Col className="loginColumn" lg={4} md={6} sm={6}>
<Card className="text-center">
<Card.Body>
<Card.Title className="p-2">User Registration</Card.Title>
<Card.Text>
<Form onSubmit={handleSubmitSignup}>
{isSubmittedSignup ? (
<Alert variant="success" className={`${fadeProp.fade} ${successAlert}`}>
Successfully Registered.
</Alert>
) : (
""
)}
{errors.msgSignup ? (
<Alert variant="danger" className={`${fadeProp.fade} ${errorAlert}`}>
{errors.msgSignup}
</Alert>
) : (
""
)}
<Form.Group className="mb-3" controlId="formBasicEmail">
<FloatingLabel controlId="floatingInput" label="Email address" className="mb-3">
<Form.Control type="email" value={user.email} name="email" placeholder="Enter email" onChange={handleChangeEmail} />
{errors.email ? <span className="text-danger float-start">{errors.email}</span> : ""}
</FloatingLabel>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<FloatingLabel controlId="floatingPassword" label="Password">
<Form.Control
type="password"
name="password"
placeholder="Password"
value={user.password}
onChange={handleChangePassword}
/>
{errors.password ? <span className="text-danger float-start">{errors.password}</span> : ""}
</FloatingLabel>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicPassword">
<FloatingLabel controlId="floatingPassword" label="Confirm password">
<Form.Control
type="password"
value={user.passwordConfirmation}
name="passwordConfirmation"
onChange={handleChangePasswordConfirmation}
placeholder="Confirm password"
/>
{errors.passwordConfirmation ? <span className="text-danger float-start">{errors.passwordConfirmation}</span> : ""}
{errors.confirm_password ? <span className="text-danger float-start">{errors.confirm_password}</span> : ""}
</FloatingLabel>
</Form.Group>
<Form.Group className="mb-3" controlId="formBasicCheckbox">
<Row className="g-2">
<Col md>
<Link to="/login" className="float-right">
Already have an Account?
</Link>
</Col>
</Row>
</Form.Group>
<div className="d-grid">
<Button type="submit" variant="primary" data-cy="submit-registration">
Sign Up
</Button>
</div>
</Form>
</Card.Text>
</Card.Body>
</Card>
</Col>
<Col />
</Row>
</Container>
);
}
export default UserRegistration;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
