英文:
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 =
/^(([^<>()[\]\\.,;:\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
});
}
};
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;
答案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 })
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论