简体   繁体   English

React 组件中的错误 - 无法验证用户注册

[英]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;

I believe you need to bind your change events.我相信您需要绑定您的更改事件。 Try adding bind(this) to your change calls, since you are not calling them with (), the event might be undefined.尝试将 bind(this) 添加到您的更改调用中,因为您没有使用 () 调用它们,所以该事件可能未定义。

onChange={handleChangePassword.bind(this)}

I also recommend collecting your separate functions into a single function for better clarity and orientation.我还建议将您的单独功能收集到单个 function 以获得更好的清晰度和方向。

function handleFormChange(event) {
    setUser({...user, [event.target.name]: event.target.value})
}

This way you can pair input names to the user object attributes and keep change function calls in a single function.这样,您可以将输入名称与用户 object 属性配对,并在单个 function 中保持更改 function 调用。

I'm not 100% sure this will help, let me know.我不是 100% 确定这会有所帮助,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM