skip to Main Content

Hello Mates I am currently developing a website and i have created a register and login form in my register form when i enter the registration details and click the submit button it shows an errorthe error in and jpeg image

I tried truobleshooting the handleInput function but stiil it is the same i have included the handle input function code below


  const handleInput = (event) => {
    setValues((prev) => ({
      ...prev,
      [event.target.name]: [event.target.value],
    }));
  };

and this is the registraton form code

SIGNUP FORM

import React, { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import Validation from "./SignupValidation";

function Signup() {
  const [values, setValues] = useState({
    username: "",
    email: "",
    password: "",
  });

  const navigate = useNavigate();

  const [errors, setErrors] = useState({});

  const handleInput = (event) => {
    setValues((prev) => ({
      ...prev,
      [event.target.name]: [event.target.value],
    }));
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    setErrors(Validation(values));
    if (Object.keys(errors).length === 0) {
      axios
        .post("http://localhost:3015/signup", values)
        .then((res) => {
          if (res.data === "Success") {
            navigate("login");
          } else {
            alert("Invalid username or password");
          }
        })
        .catch((err) => console.log(err));
    }
  };

  return (
    <div className="background">
      <div className="admin-signing">
        <h2 className="admin-login-heading">Admin Signup</h2>
        <form action="" className="signup-form" onSubmit={handleSubmit}>
          <input
            className="text-box"
            type="text"
            placeholder="Enter Username"
            name="username"
            onChange={handleInput}
          />
          <span>{errors.username && <p> {errors.username} </p>}</span>
          <input
            className="text-box"
            type="email"
            placeholder="Enter Email"
            name="email"
            onChange={handleInput}
          />
          <span>{errors.email && <p> {errors.email} </p>}</span>
          <input
            className="text-box"
            type="password"
            placeholder="Enter Password"
            name="password"
            onChange={handleInput}
          />
          <span>{errors.password && <p> {errors.password} </p>}</span>
          <button className="login-btn" type="submit">
            Signup
          </button>
        </form>
      </div>
    </div>
  );
}

export default Signup;

SIGNUP VALIDATION

export default function Validation(values){
    let error = {};
    const email_pattern = /^[a-zA-Z0-9]+@[a-zA-Z0-9]+.[A-Za-z]+$/;
    const password_pattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})/;

    if(values.username === ""){
        error.username = "Username is required";
    }else if (values.username.length < 3){
        error.username = "Username must be more than 3 characters";
    }else if (values.username.length > 15){
        error.username = "Username must be less than 15 characters";
    }

    if (!email_pattern.test(values.email)){
        error.email = "Email is invalid";
    }else if(values.email === ""){
        error.email = "Email is required";
    }else if(!email_pattern.test(values.email)){
        error.email = "Email is invalid";}

    if(values.password === ""){
        error.password = "Password is required";
    }else if (values.password.length < 6){
        error.password = "Password must be more than 6 characters";
    }else if (values.password.length > 15){
        error.password = "Password must be less than 15 characters";
    }else if(!password_pattern.test(values.password)){
        error.password = "Password must contain at least one uppercase, one lowercase, one number and one special character";
    }
}

// Compare this snippet from Front-End/src/Admin/Signup.js:

SERVER.JS

const express = require("express");
const mysql = require("mysql");
const cors = require("cors");

const app = express();
app.use(cors());
app.use(express.json());

const db = mysql.createConnection({
  host: "localhost",
  user: " root",
  password: "",
  database: "admin",
});

app.post("/signup", (req, res) => {
  const sql =
    "INSERT INTO login (`username`,`email`, `password`) VALUES (?, ?, ?)";
  const values = [req.body.username, req.body.email, req.body.password];
  db.query(sql, [values], (err, data) => {
    if (err) {
      return res.json("Error");
    }
    return res.json(data);
  });
});

app.post("/login", (req, res) => {
  const sql = "SELECT * FROM login WHERE email = ? AND password = ?";
  const values = [req.body.email, req.body.password];
  db.query(sql, values, (err, data) => {
    if (err) {
      return res.json("Error");
    }
    if (data.length > 0) {
      return res.json("Success");
    } else {
      return res.json("Invalid username or password");
    }
  });
});

app.listen(3015, () => {
  console.log("Server is running on port 3015");
});

PLEASE CAN YOU HELP ME TO GET THROUGH THIS

2

Answers


  1. First rewrite your validation function with a more clear and understandable way :

    
    const validate = (values) => {
      const errors = {};
    
      // Validate username
      if (!values.username) {
        errors.username = "Username is required";
      } else if (values.username.length < 3 || values.username.length > 15) {
        errors.username = "Username must be between 3 and 15 characters";
      }
    
      // Validate email
      if (!values.email) {
        errors.email = "Email is required";
      } else if (!isValidEmail(values.email)) {
        errors.email = "Email is invalid";
      }
    
      // Validate password
      if (!values.password) {
        errors.password = "Password is required";
      } else if (values.password.length < 6 || values.password.length > 15) {
        errors.password = "Password must be between 6 and 15 characters";
      } else if (!isValidPassword(values.password)) {
        errors.password = "Password must contain at least one uppercase, one lowercase, one number, and one special character";
      }
    
      return errors;
    };
    
    const isValidEmail = (email) => {
      const emailPattern = /^[a-zA-Z0-9]+@[a-zA-Z0-9]+.[A-Za-z]+$/;
      return emailPattern.test(email);
    };
    
    const isValidPassword = (password) => {
      const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})/;
      return passwordPattern.test(password);
    };
    
    export default validate;
    
    
    

    Second and most important, you should return errors object from validate function.

    Login or Signup to reply.
  2. Your Errors state has initial value empty object

    but you in code use errors state before submit form
    you can use optional chaining (?.)

    Example

    <span>{errors?.username && <p> {errors.username} </p>}</span>

    Remember

    When use Logical AND && and you condition is False Actually Render 0 in DOM

    Recomended use ternery Oprator

    {errors?.username ? <span> {errors.username} </span> : null}

    Read More Oure Optional Chaining

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search