skip to Main Content

how to validate login email & password using redux? a already make a handleLogin function it work fine when user input the right email&password but if user submit the wrong email&password the api crash

const handleClick = (e) => {
  e.preventDefault()
  try {
    const masuk = login(dispacth, { email, password })
    // history.push("/")
  } catch (error) {
    Swal.fire({
      position: 'top-end',
      icon: 'error',
      title: 'Email atau Password tidak sesuai',
      showConfirmButton: false,
      timer: 1500,
    })
  }
}

and my dispatch

export const login = async (dispatch, user) => {
  dispatch(loginStart())
  try {
    const res = await axios.post(BASE_URL + 'auth/login', user)
    dispatch(loginSuccess(res.data))
  } catch (error) {
    dispatch(loginFailure(error))
  }
}

2

Answers


  1. You are calling an async function without using await so the promise is not handled properly.

    Try:

    const masuk = await login(dispacth, { email, password })
    
    Login or Signup to reply.
  2. you need to run validation before the submission of the form, here is how you would do it:

    function isValidEmail(email: string): boolean {
      const regex =
        /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
    
      return regex.test(String(email).toLowerCase());
    }
    
    function isPasswordValid(password: string): boolean {
      /*
       * At least one lowercase letter ((?=.*[a-z])).
       * At least one uppercase letter ((?=.*[A-Z])).
       * At least one digit ((?=.*d)).
       * Consists of only alphanumeric characters ([a-zA-Zd]).
       * Has a minimum length of 8 characters ({8,}).
       */
      const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*d)[a-zA-Zd]{8,}$/;
    
      return regex.test(password);
    }
    
    const handleClick = async (e) => {
      e.preventDefault();
      if ((!email || !isValidEmail(email)) && (!password || !isPasswordValid(password))) {
        Swal.fire({
          position: "top-end",
          icon: "error",
          title: "Email or Password are invalid",
          showConfirmButton: false,
          timer: 1500
        });
    
        return;
      }
      try {
        const masuk = await login(dispacth, { email, password });
        // history.push("/")
      } catch (error) {
        Swal.fire({
          position: "top-end",
          icon: "error",
          title: "Email atau Password tidak sesuai",
          showConfirmButton: false,
          timer: 1500
        });
      }
    };
    

    but I recommend you to check out React Hook Form which handles everything you think of related to forms and validations

    Example with react hook form:

    make sure you have react-hook-form and yup installed in your project:

    npm install react-hook-form @hookform/resolvers yup
    
    import {yupResolver} from "@hookform/resolvers/yup";
    import {useForm} from "react-hook-form";
    import * as yup from "yup";
    
    const LoginForm = () => {
    
        const validationSchema = yup.object().shape({
            email: yup.string().email('Invalid email').required('Email is required'),
            password: yup.string().required('Password is required').min(8, 'Password must be at least 8 characters'),
        });
    
        const {register, handleSubmit, errors} = useForm({
            resolver: yupResolver(validationSchema), // Using yup validation schema
        });
    
    
        const onSubmit = (data) => {
            console.log(data); // Handle form submission here
        };
    
        return (
            <form onSubmit={handleSubmit(onSubmit)}>
                <div>
                    <label>Email</label>
                    <input {...register("email")}/>
                    {errors.email && <p role="alert">{errors.email.message}</p>}
                </div>
    
                <div>
                    <label>Password</label>
                    <input type="password" {...register("password")}/>
                    {errors.password && <p role="alert">{errors.password.message}</p>}
                </div>
    
                <button type="submit">Submit</button>
            </form>
        );
    };
    
    export default LoginForm;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search