如何使用Redux验证电子邮件和密码

rta7y2nd  于 2023-10-19  发布在  其他
关注(0)|答案(2)|浏览(217)

如何使用redux验证登录邮箱和密码?a已经做了一个登录功能,当用户输入正确的电子邮件和密码时,它工作正常,但如果用户提交错误的电子邮件和密码,API崩溃

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,
    })
  }
}

还有我的派遣

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))
  }
}
gpfsuwkq

gpfsuwkq1#

你需要在提交表单之前运行验证,这里是你如何做的:

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-Z\d]).
   * Has a minimum length of 8 characters ({8,}).
   */
  const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{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
    });
  }
};

但我建议您查看React Hook Form,它可以处理与表单和验证相关的所有内容
react hook形式的示例:
确保你的项目中安装了react-hook-form和yup:

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;
ubby3x7f

ubby3x7f2#

你调用了一个没有使用await的promise函数,所以promise没有被正确处理。
试试看:

const masuk = await login(dispacth, { email, password })

相关问题