add validation

This commit is contained in:
karimaldeen 2024-09-14 11:55:13 +03:00
parent 6dc2e5fe7c
commit 0586a88cab
13 changed files with 242 additions and 100 deletions

View File

@ -7,6 +7,7 @@ import { useEffect } from "react";
const useFormField = (name: string, props?: any) => {
const [field, meta] = useField({ name, ...props });
const { t } = useTranslation();
const formik = useFormikContext<any>();

View File

@ -29,6 +29,7 @@ const FormikFormModel: React.FC<FormikFormProps> = ({
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={handleSubmit}
>
{(formik) => {
useEffect(() => {

View File

@ -19,6 +19,7 @@ import { Question } from "../../../types/Item";
import BaseForm from "./Model/Malty/Form";
import ModelForm from "./Model/ModelForm";
import { toast } from "react-toastify";
import { Form, Formik } from "formik";
const AcceptModal = lazy(() => import("./Model/AcceptModal"));
const AddPage: React.FC = () => {
@ -30,12 +31,7 @@ const AddPage: React.FC = () => {
const [t] = useTranslation();
const { subject_id, lesson_id } = useParams<ParamsEnum>();
console.log(objectToEdit, "objectToEdit");
const handleSubmit = (
values: any,
{ resetForm }: { resetForm: () => void },
) => {
const handleSubmit = ( values: any) => {
const DataToSend = structuredClone(values);
setTagsSearch(null);
console.log(1);
@ -95,17 +91,6 @@ const AddPage: React.FC = () => {
};
});
if (answers?.length > 0) {
const isValidAnswers = answers?.some(
(answer: any) => answer?.isCorrect === 1,
);
console.log(!isValidAnswers);
if (!isValidAnswers) {
toast.error(t("validation.at_least_one_answer_should_be_correct"));
return;
}
}
const NewQuestion = {
...values,
@ -122,6 +107,54 @@ const AddPage: React.FC = () => {
}
};
const handleValidateSingleQuestion = (values:any)=>{
const haveAnswers = values?.answers?.length > 0 ;
const haveMoreThanOneAnswer = haveAnswers && values?.answers?.length > 1;
const haveOneAnswerRight = haveMoreThanOneAnswer && values?.answers?.some((item:any)=> item?.isCorrect === 1 || item.isCorrect === true )
if(!haveAnswers){
return false ;
}
if(!haveMoreThanOneAnswer){
toast.error(t("validation.it_should_have_more_than_one_answers")) ;
return false ;
}
if(!haveOneAnswerRight){
toast.error(t("validation.it_should_have_more_than_one_correct_answers")) ;
return false ;
}
}
const handleValidateBaseQuestion = (values: any) => {
const haveAnswers = values?.Questions?.every((Question: any, QuestionsIndex: number) => {
const answers = Question?.answers;
const haveAnswers = answers?.length > 0;
const haveMoreThanOneAnswer = haveAnswers && answers?.length > 1;
const haveOneAnswerRight =
haveMoreThanOneAnswer && answers?.some((item: any) => item?.isCorrect === 1 || item.isCorrect === true);
if (!haveAnswers) {
toast.error(t("validation.it_should_have_more_than_one_answers"));
return false;
}
if (!haveMoreThanOneAnswer) {
toast.error(t("validation.it_should_have_more_than_one_answers"));
return false;
}
if (!haveOneAnswerRight) {
toast.error(t("validation.it_should_have_more_than_one_correct_answers"));
return false;
}
return true;
});
console.log(haveAnswers, "haveAnswers");
};
const navigate = useNavigate();
const handleCancel = () => {
@ -129,7 +162,6 @@ const AddPage: React.FC = () => {
};
const Loading = LoadingAsync || isLoading
useEffect(() => {
console.log("all api success");
if (isSuccess) {
setSuccess(true);
}
@ -137,19 +169,28 @@ const AddPage: React.FC = () => {
if (isBseQuestion) {
return (
<div className="exercise_add">
<FormikForm
handleSubmit={handleSubmit}
<Formik
onSubmit={handleSubmit}
initialValues={getInitialValuesBase(objectToEdit)}
validationSchema={getValidationSchemaBase}
enableReinitialize
>
{({ values,handleSubmit }) => (
<Form className="w-100">
<main className="w-100 exercise_add_main">
<Header />
<BaseForm />
<div className="exercise_add_buttons">
<div onClick={handleCancel}>{t("practical.back")}</div>
<button disabled={Loading} className="relative" type="submit">
<button disabled={Loading} className="relative" type="submit"
onClick={()=>{handleValidateBaseQuestion(values) ;handleSubmit(values)}}
onSubmit={()=>{handleValidateBaseQuestion(values) ;handleSubmit(values) }}
>
{t("practical.add")}
{Loading && (
@ -160,7 +201,9 @@ const AddPage: React.FC = () => {
</button>
</div>
</main>
</FormikForm>
</Form>
)}
</Formik>
<Suspense fallback={<Spin />}>
<AcceptModal />
</Suspense>
@ -169,18 +212,29 @@ const AddPage: React.FC = () => {
}
return (
<div className="exercise_add">
<FormikForm
handleSubmit={handleSubmit}
<Formik
enableReinitialize={true}
initialValues={getInitialValues(objectToEdit)}
validationSchema={getValidationSchema}
onSubmit={(values) => {
handleSubmit(values);
}}
>
{({ values,handleSubmit }) => (
<Form className="w-100">
<main className="w-100 exercise_add_main">
<Header />
<ModelForm />
<div className="exercise_add_buttons">
<div onClick={handleCancel}>{t("practical.back")}</div>
<button disabled={Loading} className="relative" type="submit">
<button
disabled={Loading}
className="relative"
onClick={()=>{handleValidateSingleQuestion(values) ;handleSubmit(values)}}
onSubmit={()=>{handleValidateSingleQuestion(values) ;handleSubmit(values) }}
type="submit"
>
{t("practical.add")}
{Loading && (
@ -191,7 +245,10 @@ const AddPage: React.FC = () => {
</button>
</div>
</main>
</FormikForm>
</Form>
)}
</Formik>
<Suspense fallback={<Spin />}>
<AcceptModal />
</Suspense>

View File

@ -25,6 +25,7 @@ import BaseForm from "./Model/Malty/Form";
import { Question } from "../../../types/Item";
import { toast } from "react-toastify";
import { deletePathSegments } from "../../../utils/deletePathSegments";
import { Form, Formik } from "formik";
const EditPage: React.FC = () => {
const { subject_id, lesson_id, question_id } = useParams<ParamsEnum>();
@ -187,6 +188,54 @@ const EditPage: React.FC = () => {
};
const handleValidateSingleQuestion = (values:any)=>{
const haveAnswers = values?.answers?.length > 0 ;
const haveMoreThanOneAnswer = haveAnswers && values?.answers?.length > 1;
const haveOneAnswerRight = haveMoreThanOneAnswer && values?.answers?.some((item:any)=> item?.isCorrect === 1 || item.isCorrect === true )
if(!haveAnswers){
return false ;
}
if(!haveMoreThanOneAnswer){
toast.error(t("validation.it_should_have_more_than_one_answers")) ;
return false ;
}
if(!haveOneAnswerRight){
toast.error(t("validation.it_should_have_more_than_one_correct_answers")) ;
return false ;
}
}
const handleValidateBaseQuestion = (values: any) => {
const haveAnswers = values?.Questions?.every((Question: any, QuestionsIndex: number) => {
const answers = Question?.answers;
const haveAnswers = answers?.length > 0;
const haveMoreThanOneAnswer = haveAnswers && answers?.length > 1;
const haveOneAnswerRight =
haveMoreThanOneAnswer && answers?.some((item: any) => item?.isCorrect === 1 || item.isCorrect === true);
if (!haveAnswers) {
toast.error(t("validation.it_should_have_more_than_one_answers"));
return false;
}
if (!haveMoreThanOneAnswer) {
toast.error(t("validation.it_should_have_more_than_one_answers"));
return false;
}
if (!haveOneAnswerRight) {
toast.error(t("validation.it_should_have_more_than_one_correct_answers"));
return false;
}
return true;
});
console.log(haveAnswers, "haveAnswers");
};
useEffect(() => {
if (isSuccess) {
toast.success(t("validation.the_possess_done_successful"));
@ -202,11 +251,15 @@ const EditPage: React.FC = () => {
if (objectToEdit?.isBase) {
return (
<div className="exercise_add">
<FormikForm
handleSubmit={handleSubmit}
<Formik
onSubmit={handleSubmit}
initialValues={getInitialValuesBase(objectToEdit)}
validationSchema={getValidationSchemaBase}
enableReinitialize
>
{({ values,handleSubmit }) => (
<Form className="w-100">
<main className="w-100 exercise_add_main">
{/* <Header/> */}
<header className="exercise_add_header mb-4">
@ -218,8 +271,10 @@ const EditPage: React.FC = () => {
<BaseForm />
<div className="exercise_add_buttons">
<div onClick={handleCancel}>{t("practical.back")}</div>
<button disabled={Loading} className="relative" type="submit">
{t("practical.edit")}
<button disabled={Loading} className="relative" type="submit"
onClick={()=>{handleValidateBaseQuestion(values) ;handleSubmit(values)}}
onSubmit={()=>{handleValidateBaseQuestion(values) ;handleSubmit(values) }}
> {t("practical.edit")}
{Loading && (
<span className="Spinier_Div">
@ -229,18 +284,27 @@ const EditPage: React.FC = () => {
</button>
</div>
</main>
</FormikForm>
</Form>
)}
</Formik>
</div>
);
}
return (
<div className="exercise_add">
<FormikForm
handleSubmit={handleSubmit}
<Formik
enableReinitialize={true}
initialValues={getInitialValues(objectToEdit)}
validationSchema={getValidationSchema}
onSubmit={(values) => {
handleSubmit(values);
}}
>
{({ values,handleSubmit }) => (
<Form className="w-100">
<main className="w-100 exercise_add_main">
{/* <Header/> */}
<header className="exercise_add_header mb-4">
@ -252,8 +316,13 @@ const EditPage: React.FC = () => {
<ModelForm />
<div className="exercise_add_buttons">
<div onClick={handleCancel}>{t("practical.back")}</div>
<button disabled={Loading} className="relative" type="submit">
{t("practical.edit")}
<button
disabled={Loading}
className="relative"
onClick={()=>{handleValidateSingleQuestion(values) ;handleSubmit(values)}}
onSubmit={()=>{handleValidateSingleQuestion(values) ;handleSubmit(values) }}
type="submit"
> {t("practical.edit")}
{Loading && (
<span className="Spinier_Div">
@ -263,7 +332,11 @@ const EditPage: React.FC = () => {
</button>
</div>
</main>
</FormikForm>
</Form>
)}
</Formik>
</div>
);
};

View File

@ -39,6 +39,7 @@ const ChoiceFields = ({ index, data }: { index: number; data: Choice }) => {
name={index}
id={`choice_${index + 1}`}
type="TextArea"
/>
<ImageBoxField name={`answers.${index}.content_image`} />

View File

@ -86,6 +86,8 @@ const Form = () => {
},
);
return (
<Row className="w-100 exercise_form_container">
<div className="exercise_form">

View File

@ -41,14 +41,10 @@ const MaltySelectTag = ({ parent_index }: { parent_index: number }) => {
? [{ id: searchValue, name: searchValue }]
: [];
console.log(options);
const value =
formik?.values?.Questions[parent_index]?.tags?.map(
(item: any) => item?.id ?? item,
) ?? [];
console.log(formik?.values?.Questions[parent_index]);
console.log(value);
const AllOptions = [...options, ...additionalData];

View File

@ -20,7 +20,7 @@ const Form = () => {
const handleAddChoice = (fromKeyCombination: boolean = false) => {
formik.setFieldValue("answers", [
...((formik?.values as any)?.answers as Choice[]),
...(formik?.values?.answers ?? []) ,
{
content: null,
content_image: null,
@ -42,13 +42,12 @@ const Form = () => {
useEffect(() => {
if (Success) {
formik?.setValues({});
formik.setErrors({});
formik.resetForm()
setSuccess(false);
console.log(formik.errors);
}
}, [Success]);
return (
<Row className="w-100 exercise_form_container">
<div className="exercise_form">
@ -62,7 +61,7 @@ const Form = () => {
</div>
<Choices />
{formik?.values?.answers?.length < 5 && (
{(formik?.values?.answers === null || formik?.values?.answers === undefined || formik?.values?.answers?.length < 5) && (
<p className="add_new_button">
<FaCirclePlus onClick={() => handleAddChoice()} size={23} />{" "}
{t("header.add_new_choice")}

View File

@ -16,7 +16,7 @@ export const getInitialValues = (objectToEdit: Question): any => {
hint: objectToEdit?.hint ?? null,
isBase: 0,
parent_id: objectToEdit?.parent_id ?? "",
answers: objectToEdit?.answers ?? [],
answers: objectToEdit?.answers ?? null,
tags: tags ?? [],
};
};
@ -32,6 +32,19 @@ export const getValidationSchema = () => {
content_image: Yup.string().nullable(),
isCorrect: Yup.boolean(),
}),
).min(2).nullable().test(
"at-least-one-correct",
"At least one answer must be correct",
(answers: any) => {
console.log(answers, "answers");
if(answers === null){
return true
}
return answers?.some(
(answer: any) =>
answer?.isCorrect === true || answer?.isCorrect === 1,
);
},
),
});
};
@ -42,10 +55,18 @@ export const getInitialValuesBase = (objectToEdit: Question): any => {
id: tag?.id,
name: tag?.name,
}));
console.log(item, "item");
const newAnswers = item?.answers?.map((item:any)=>{
return {
...item,
content : item?.content ?? null
}
})
console.log(newAnswers,"newAnswers");
return {
...item,
answer:newAnswers,
canAnswersBeShuffled: objectToEdit?.canAnswersBeShuffled ? 1 : 0,
hint: objectToEdit?.hint ?? "",
isBase: 0,
@ -53,7 +74,7 @@ export const getInitialValuesBase = (objectToEdit: Question): any => {
};
});
const questions = newQuestions ?? [];
const questions = newQuestions ?? [{answers:[]}];
return {
id: objectToEdit?.id ?? null,
@ -84,12 +105,11 @@ export const getValidationSchemaBase = () => {
answer_image: Yup.string().nullable(),
isCorrect: Yup.boolean(),
}),
)
).min(2)
.test(
"at-least-one-correct",
"At least one answer must be correct",
(answers: any) => {
console.log(answers, "answers");
return answers.some(
(answer: any) =>
@ -98,7 +118,7 @@ export const getValidationSchemaBase = () => {
},
),
}),
),
).min(1),
});
};

View File

@ -14,6 +14,7 @@ import {
} from "../../config/AppKey";
import useFormatAuthDataToSelect from "../../utils/useFormatAuthDataToSelect";
import { useTranslation } from "react-i18next";
import ValidationField from "../../Components/ValidationField/ValidationField";
type FormFieldType = {
isLoading: boolean;
@ -25,22 +26,11 @@ const FormField = ({ isLoading }: FormFieldType) => {
<Form className="AuthForm">
{/* <Image style={{background:"#000"}} src="../App/Logo.png" /> */}
<h2>{t("تسجيل الدخول إلى حسابك")}</h2>
<div className="AuthInput">
<label className="form-label" htmlFor="username">
{t("input.Username")}
</label>
<Field
placeholder={t("input.Username")}
as={Input}
type="text"
id="username"
name="username"
className="Input"
size="large"
/>
</div>
<div className="AuthInput">
<ValidationField name="username" label="username" />
<ValidationField name="password" label="password" />
{/* <div className="AuthInput">
<label className="form-label" htmlFor="password">
{t("input.Password")}
</label>
@ -53,7 +43,7 @@ const FormField = ({ isLoading }: FormFieldType) => {
className="passwordInput"
size="large"
/>
</div>
</div> */}
<button disabled={isLoading} type="submit" className="auth_submit_button">
{t("practical.login")}

View File

@ -4,7 +4,7 @@ import useAuthState from "../../zustand/AuthState";
import useNavigateOnSuccess from "../../Hooks/useNavigateOnSuccess";
import { useLoginAdmin } from "../../api/auth";
import FormField from "./FormField";
import { initialValues } from "./formutils";
import { initialValues, validationSchema } from "./formutils";
import { FormValues } from "../../types/Auth";
import { toast } from "react-toastify";
import { useTranslation } from "react-i18next";
@ -39,7 +39,7 @@ const LoginForm = () => {
return (
<div className="LoginForm">
<Formik initialValues={initialValues} onSubmit={handelSubmit}>
<Formik initialValues={initialValues} onSubmit={handelSubmit} validationSchema={validationSchema} >
{(formikProps) => <FormField isLoading={isLoading} />}
</Formik>
</div>

View File

@ -2,8 +2,8 @@ import * as Yup from "yup";
import { FormValues } from "../../types/Auth";
export const validationSchema = Yup.object().shape({
username: Yup.string().required("Username is required"),
password: Yup.string().required("Password is required"),
username: Yup.string().required("validation.required"),
password: Yup.string().required("validation.required").min(8,"validation.Password_must_be_at_least_8_characters_long"),
});
export const initialValues: FormValues = {

View File

@ -46,7 +46,9 @@
"grade_to_pass_must_be_less_than_max_grade": "يجب أن تكون درجة النجاح أقل من الحد الأقصى للدرجة",
"max_mark_must_be_greater_than_min_mark_to_pass": "يجب ان تكون اكبر من علامة النجاح",
"Sorry, the question must have at least one option": "عذرًا، يجب أن يحتوي السؤال على خيار واحد على الأقل",
"at_least_one_answer_should_be_correct": "يجب أن تكون إجابة واحدة صحيحة"
"at_least_one_answer_should_be_correct": "يجب أن تكون إجابة واحدة صحيحة",
"it_should_have_more_than_one_answers":"يجب أن يحتوي على أكثر من إجابة",
"it_should_have_more_than_one_correct_answers":"يجب أن يحتوي على إجابة صحيحة"
},
"header": {
"register_students": "تسجيل الطلاب",