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

huangapple go评论103阅读模式
英文:

How to validate email&password using redux

问题

const handleClick = (e) => {
  e.preventDefault()
  try {
    const masuk = login(dispatch, { email, password })
    // history.push("/")
  } catch (error) {
    Swal.fire({
      position: 'top-end',
      icon: 'error',
      title: 'Email或密码不正确',
      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))
  }
}
英文:

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

答案1

得分: 1

你需要在提交表单之前运行验证,以下是如何执行此操作的代码部分:

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 Form的示例:

确保你的项目中安装了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), // 使用yup验证模式
    });


    const onSubmit = (data) => {
        console.log(data); // 在此处理表单提交
    };

    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;

<details>
<summary>英文:</summary>
you need to run validation before the submission of the form, here is how you would do it:
```js
function isValidEmail(email: string): boolean {
const regex =
/^(([^&lt;&gt;()[\]\\.,;:\s@&quot;]+(\.[^&lt;&gt;()[\]\\.,;:\s@&quot;]+)*)|(&quot;.+&quot;))@((\[[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) =&gt; {
e.preventDefault();
if ((!email || !isValidEmail(email)) &amp;&amp; (!password || !isPasswordValid(password))) {
Swal.fire({
position: &quot;top-end&quot;,
icon: &quot;error&quot;,
title: &quot;Email or Password are invalid&quot;,
showConfirmButton: false,
timer: 1500
});
return;
}
try {
const masuk = await login(dispacth, { email, password });
// history.push(&quot;/&quot;)
} catch (error) {
Swal.fire({
position: &quot;top-end&quot;,
icon: &quot;error&quot;,
title: &quot;Email atau Password tidak sesuai&quot;,
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 &quot;@hookform/resolvers/yup&quot;;
import {useForm} from &quot;react-hook-form&quot;;
import * as yup from &quot;yup&quot;;

const LoginForm = () =&gt; {

    const validationSchema = yup.object().shape({
        email: yup.string().email(&#39;Invalid email&#39;).required(&#39;Email is required&#39;),
        password: yup.string().required(&#39;Password is required&#39;).min(8, &#39;Password must be at least 8 characters&#39;),
    });

    const {register, handleSubmit, errors} = useForm({
        resolver: yupResolver(validationSchema), // Using yup validation schema
    });


    const onSubmit = (data) =&gt; {
        console.log(data); // Handle form submission here
    };

    return (
        &lt;form onSubmit={handleSubmit(onSubmit)}&gt;
            &lt;div&gt;
                &lt;label&gt;Email&lt;/label&gt;
                &lt;input {...register(&quot;email&quot;)}/&gt;
                {errors.email &amp;&amp; &lt;p role=&quot;alert&quot;&gt;{errors.email.message}&lt;/p&gt;}
            &lt;/div&gt;

            &lt;div&gt;
                &lt;label&gt;Password&lt;/label&gt;
                &lt;input type=&quot;password&quot; {...register(&quot;password&quot;)}/&gt;
                {errors.password &amp;&amp; &lt;p role=&quot;alert&quot;&gt;{errors.password.message}&lt;/p&gt;}
            &lt;/div&gt;

            &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;
        &lt;/form&gt;
    );
};

export default LoginForm;

答案2

得分: 0

您在调用一个异步函数时没有使用await,因此承诺未被正确处理。

尝试:

const masuk = await login(dispatch, { email, password })
英文:

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

Try:

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

huangapple
  • 本文由 发表于 2023年8月10日 21:27:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76876181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定