debug ModalRegistration and

RegistrationForCandidate
This commit is contained in:
Никита Губарь 2023-12-29 12:23:54 +03:00
parent 94a13f4903
commit 4b0176079e
5 changed files with 128 additions and 197 deletions

View File

@ -1,2 +0,0 @@
REACT_APP_API_URL = https://dev.itguild.info/api
REACT_APP_BASE_URL = https://dev.itguild.info/api

View File

@ -87,12 +87,12 @@ export const AuthBox = ({ title }) => {
)} )}
<form ref={ref} className="auth-box__form"> <form ref={ref} className="auth-box__form">
<label htmlFor="e-mail">Ваш e-mail</label> <label htmlFor="e-mail">Ваш e-mail</label>
<input id="e-mail" type="text" name="email" placeholder="E-mail" /> <input id="loginEmail" type="text" name="email" placeholder="E-mail" />
<label htmlFor="password">Ваш пароль</label> <label htmlFor="password">Ваш пароль</label>
<div className="inputWrapper"> <div className="inputWrapper">
<input <input
id="password" id="loginPassword"
type={showPassword ? "text" : "password"} type={showPassword ? "text" : "password"}
name="password" name="password"
placeholder="Пароль" placeholder="Пароль"

View File

@ -1,7 +1,6 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { apiRequest } from "@api/request"; import { useFormValidation } from "@hooks/useFormValidation";
import { useNotification } from "@hooks/useNotification"; import { useNotification } from "@hooks/useNotification";
import BaseButton from "@components/Common/BaseButton/BaseButton"; import BaseButton from "@components/Common/BaseButton/BaseButton";
@ -15,98 +14,51 @@ import telegramLogo from "assets/icons/tgLogo.svg";
import "./modalRegistration.scss"; import "./modalRegistration.scss";
export const ModalRegistration = ({ active, setActive }) => { export const ModalRegistration = ({ active, setActive }) => {
const [inputsValue, setInputsValue] = useState({ const [loader, setLoader] = useState(false);
userName: "",
const fields = {
username: "",
email: "", email: "",
password: "", password: "",
secondPassword: "" secondPassword: ""
});
const [inputsError, setInputsError] = useState({
name: false,
email: false,
password: false,
secondPassword: false
});
const [loader, setLoader] = useState(false);
const validateEmail = (email) => {
// регулярное выражение для проверки email
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// возвращаем true, если email проходит проверку, и false, если нет
return re.test(email);
}; };
const closeModal = () => {
setActive(false);
handleClearForm();
};
const apiEndpoint = "/register/sign-up";
const { showNotification } = useNotification(); const { showNotification } = useNotification();
const showNotificationError = () => {
const validateForm = () => { showNotification({
if (inputsValue.password.length < 6) { show: true,
setInputsError((prevValue) => ({ ...prevValue, password: true })); text: "Аккаунт с таким логином или email уже существует",
} type: "error"
if (inputsValue.password !== inputsValue.secondPassword) { });
setInputsError((prevValue) => ({ ...prevValue, secondPassword: true }));
}
if (inputsValue.userName.length < 2) {
setInputsError((prevValue) => ({ ...prevValue, name: true }));
}
if (!validateEmail(inputsValue.email)) {
setInputsError((prevValue) => ({ ...prevValue, email: true }));
}
if (
inputsValue.password.length < 6 ||
inputsValue.userName.length < 6 ||
!validateEmail(inputsValue.email)
) {
return true;
}
}; };
const showNotificationTrue = () => {
const submitHandler = () => { showNotification({
if (validateForm()) { show: true,
return; text: "Аккаунт успешно создан",
} type: "success"
setLoader(true);
apiRequest("/register/sign-up", {
method: "POST",
data: {
username: inputsValue.userName,
email: inputsValue.email,
password: inputsValue.password
}
}).then((data) => {
setLoader(false);
if (!data) {
showNotification({
show: true,
text: "Аккаунт с таким логином или email уже существует",
type: "error"
});
} else {
closeModal();
showNotification({
show: true,
text: "Аккаунт успешно создан",
type: "success"
});
}
}); });
}; };
const closeModal = () => { const {
setInputsValue({ formData,
userName: "", validationErrors,
email: "", handleChange,
password: "" handleSubmit,
}); handleClearForm
setInputsError({ } = useFormValidation(
name: false, apiEndpoint,
email: false, fields,
password: false showNotificationError,
}); showNotificationTrue,
setActive(false); closeModal
}; );
return ( return (
<ModalLayout active={active} setActive={closeModal} styles={"registration"}> <ModalLayout active={active} setActive={closeModal} styles={"registration"}>
<div className="registration-body__main"> <div className="registration-body__main">
@ -122,43 +74,25 @@ export const ModalRegistration = ({ active, setActive }) => {
<div className="inputContainer"> <div className="inputContainer">
<h5>Ваше имя</h5> <h5>Ваше имя</h5>
<input <input
className={inputsError.name ? "error" : ""} className={validationErrors.username ? "error" : ""}
onChange={(e) => { onChange={handleChange}
setInputsError({ value={formData.username}
name: false,
email: false,
password: false
});
setInputsValue((prevValue) => ({
...prevValue,
userName: e.target.value
}));
}}
value={inputsValue.userName}
placeholder="Имя" placeholder="Имя"
id="username"
/> />
{inputsError.name && <span>Минимум 2 символа</span>} <span>{validationErrors.username}</span>
</div> </div>
<div className="inputContainer"> <div className="inputContainer">
<h5>E-mail</h5> <h5>E-mail</h5>
<input <input
type="email" type="email"
className={inputsError.email ? "error" : ""} className={validationErrors.email ? "error" : ""}
onChange={(e) => { onChange={handleChange}
setInputsError({ value={formData.email}
name: false,
email: false,
password: false
});
setInputsValue((prevValue) => ({
...prevValue,
email: e.target.value
}));
}}
value={inputsValue.email}
placeholder="Почта" placeholder="Почта"
id="email"
/> />
{inputsError.email && <span>Введите корректный e-mail</span>} <span>{validationErrors.email}</span>
</div> </div>
</div> </div>
@ -166,46 +100,26 @@ export const ModalRegistration = ({ active, setActive }) => {
<div className="inputContainer"> <div className="inputContainer">
<h5>Пароль</h5> <h5>Пароль</h5>
<input <input
className={inputsError.password ? "error" : ""} className={validationErrors.password ? "error" : ""}
type="password" type="password"
onChange={(e) => { onChange={handleChange}
setInputsError({ value={formData.password}
name: false,
email: false,
password: false
});
setInputsValue((prevValue) => ({
...prevValue,
password: e.target.value
}));
}}
value={inputsValue.password}
placeholder="Пароль" placeholder="Пароль"
id="password"
/> />
{inputsError.password && <span>Минимум 6 символов</span>} <span>{validationErrors.password}</span>
</div> </div>
<div className="inputContainer"> <div className="inputContainer">
<h5>Повторите пароль</h5> <h5>Повторите пароль</h5>
<input <input
className={inputsError.secondPassword ? "error" : ""} className={validationErrors.secondPassword ? "error" : ""}
type="password" type="password"
onChange={(e) => { onChange={handleChange}
setInputsError({ value={formData.secondPassword}
name: false,
email: false,
secondPassword: false
});
setInputsValue((prevValue) => ({
...prevValue,
secondPassword: e.target.value
}));
}}
value={inputsValue.secondPassword}
placeholder="Пароль" placeholder="Пароль"
id="secondPassword"
/> />
{inputsError.secondPassword && ( <span>{validationErrors.secondPassword}</span>
<span>Пароли должны совпадать</span>
)}
</div> </div>
</div> </div>
</div> </div>
@ -217,7 +131,10 @@ export const ModalRegistration = ({ active, setActive }) => {
<BaseButton <BaseButton
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
submitHandler(); setLoader(true);
handleSubmit(e);
setLoader(false);
closeModal();
}} }}
styles="button-box__submit" styles="button-box__submit"
> >

View File

@ -23,9 +23,9 @@ export const useFormValidation = (
// Функция для валидации формы // Функция для валидации формы
const validateForm = () => { const validateForm = () => {
const errors = {}; const errors = {};
if (formData.name != undefined) { if (formData.username != undefined) {
if (formData.name.trim() === "") { if (formData.username.trim() === "") {
errors.name = "Имя обязательно к заполнению"; errors.username = "Имя обязательно к заполнению";
} }
} }
@ -66,23 +66,39 @@ export const useFormValidation = (
return Object.keys(errors).length === 0; return Object.keys(errors).length === 0;
}; };
// Функция отчистки формы
const handleClearForm = () => {
const clearedFormData = Object.fromEntries(
Object.keys(formData).map((key) => [key, ""])
);
setFormData(clearedFormData);
const clearedValidationErrors = Object.fromEntries(
Object.keys(validationErrors).map((key) => [key, ""])
);
setValidationErrors(clearedValidationErrors);
};
// Функция для обработки отправки формы // Функция для обработки отправки формы
const handleSubmit = async (e) => { const handleSubmit = async (e) => {
e.preventDefault(); e.preventDefault();
// Проверка валидации формы // Проверка валидации формы
if (validateForm()) { if (validateForm()) {
try { let newformData = { ...formData };
const response = await apiRequest(apiEndpoint, { delete newformData.secondPassword;
method: "POST",
data: formData
});
if (!response) { try {
showNotificationError(); apiRequest(apiEndpoint, {
} else { method: "POST",
showNotificationTrue(); data: newformData
} }).then((data) => {
if ("errors" in data) {
showNotificationError();
} else {
handleClearForm();
showNotificationTrue();
}
});
} catch (error) { } catch (error) {
console.error("Error submitting form:", error); console.error("Error submitting form:", error);
} }
@ -93,6 +109,7 @@ export const useFormValidation = (
formData, formData,
validationErrors, validationErrors,
handleChange, handleChange,
handleSubmit handleSubmit,
handleClearForm
}; };
}; };

View File

@ -17,7 +17,7 @@ export const RegistrationForCandidate = () => {
const apiEndpoint = "/register/sign-up"; const apiEndpoint = "/register/sign-up";
const fields = { const fields = {
name: "", username: "",
summary: "", summary: "",
email: "", email: "",
tg: "", tg: "",
@ -41,12 +41,13 @@ export const RegistrationForCandidate = () => {
}); });
}; };
const form = useFormValidation( const { formData, validationErrors, handleChange, handleSubmit } =
apiEndpoint, useFormValidation(
fields, apiEndpoint,
showNotificationError, fields,
showNotificationTrue showNotificationError,
); showNotificationTrue
);
return ( return (
<div className="registrationCandidate"> <div className="registrationCandidate">
@ -79,81 +80,79 @@ export const RegistrationForCandidate = () => {
{/* форма регистрации */} {/* форма регистрации */}
<form <form
className="registrationCandidate__form" className="registrationCandidate__form"
onSubmit={form.handleSubmit} onSubmit={handleSubmit}
> >
<div className="registrationCandidate__form__input"> <div className="registrationCandidate__form__input">
<label htmlFor="name">Ваше имя</label> <label htmlFor="name">Ваше имя</label>
<input <input
className={form.validationErrors.name ? "error" : ""} className={validationErrors.username ? "error" : ""}
value={form.formData.name} value={formData.username}
onChange={form.handleChange} onChange={handleChange}
id="name" id="username"
type="text" type="text"
placeholder="Имя" placeholder="Имя"
/> />
<span>{form.validationErrors.name}</span> <span>{validationErrors.username}</span>
</div> </div>
<div className="registrationCandidate__form__input"> <div className="registrationCandidate__form__input">
<label htmlFor="summary">Если есть ссылка на резюме</label> <label htmlFor="summary">Если есть ссылка на резюме</label>
<input <input
className={form.validationErrors.summary ? "error" : ""} className={validationErrors.summary ? "error" : ""}
value={form.formData.summary} value={formData.summary}
onChange={form.handleChange} onChange={handleChange}
id="summary" id="summary"
type="url" type="url"
placeholder="Резюме" placeholder="Резюме"
/> />
<span>{form.validationErrors.summary}</span> <span>{validationErrors.summary}</span>
</div> </div>
<div className="registrationCandidate__form__input"> <div className="registrationCandidate__form__input">
<label htmlFor="email">Ваш e-mail</label> <label htmlFor="email">Ваш e-mail</label>
<input <input
className={form.validationErrors.email ? "error" : ""} className={validationErrors.email ? "error" : ""}
value={form.formData.email} value={formData.email}
onChange={form.handleChange} onChange={handleChange}
id="email" id="email"
type="email" type="email"
placeholder="E-mail" placeholder="E-mail"
/> />
<span>{form.validationErrors.email}</span> <span>{validationErrors.email}</span>
</div> </div>
<div className="registrationCandidate__form__input"> <div className="registrationCandidate__form__input">
<label htmlFor="tg">Ваш telegram</label> <label htmlFor="tg">Ваш telegram</label>
<input <input
className={form.validationErrors.tg ? "error" : ""} className={validationErrors.tg ? "error" : ""}
value={form.formData.tg} value={formData.tg}
onChange={form.handleChange} onChange={handleChange}
id="tg" id="tg"
type="text" type="text"
placeholder="Telegram" placeholder="Telegram"
/> />
<span>{form.validationErrors.tg}</span> <span>{validationErrors.tg}</span>
</div> </div>
<div className="registrationCandidate__form__input"> <div className="registrationCandidate__form__input">
<label htmlFor="password">Придумайте пароль</label> <label htmlFor="password">Придумайте пароль</label>
<input <input
className={form.validationErrors.password ? "error" : ""} className={validationErrors.password ? "error" : ""}
value={form.formData.password} value={formData.password}
onChange={form.handleChange} onChange={handleChange}
id="password" id="password"
type="password" type="password"
placeholder="Пароль" placeholder="Пароль"
/> />
<span>{form.validationErrors.password}</span> <span>{validationErrors.password}</span>
</div> </div>
<div className="registrationCandidate__form__input"> <div className="registrationCandidate__form__input">
<label htmlFor="secondPassword">Повторите пароль</label> <label htmlFor="secondPassword">Повторите пароль</label>
<input <input
className={ className={validationErrors.secondPassword ? "error" : ""}
form.validationErrors.secondPassword ? "error" : "" value={formData.secondPassword}
} onChange={handleChange}
value={form.formData.secondPassword}
onChange={form.handleChange}
id="secondPassword" id="secondPassword"
type="password" type="password"
placeholder="Пароль" placeholder="Пароль"
/> />
<span>{form.validationErrors.secondPassword}</span> <span>{validationErrors.secondPassword}</span>
</div> </div>
<div className="registrationCandidate__form__submit"> <div className="registrationCandidate__form__submit">
<button type="submit">Отправить</button> <button type="submit">Отправить</button>