Skip to content

Commit

Permalink
Add validation to inventory management page
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashesh3 committed Jun 26, 2023
1 parent f404134 commit 0c03edc
Showing 1 changed file with 55 additions and 2 deletions.
57 changes: 55 additions & 2 deletions src/Components/Facility/AddInventoryForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,15 @@ const initForm = {
unit: "",
isIncoming: false,
};

const initError = Object.assign(
{},
...Object.keys(initForm).map((k) => ({ [k]: "" }))
);

const initialState = {
form: { ...initForm },
errors: { ...initError },
};

const inventoryFormReducer = (state = initialState, action: any) => {
Expand All @@ -37,7 +44,7 @@ const inventoryFormReducer = (state = initialState, action: any) => {
form: action.form,
};
}
case "set_error": {
case "set_errors": {
return {
...state,
errors: action.errors,
Expand Down Expand Up @@ -180,8 +187,51 @@ export const AddInventoryForm = (props: any) => {
}
};

const validateForm = () => {
const errors = { ...initError };
let invalidForm = false;

Object.keys(state.form).forEach((field) => {
switch (field) {
case "id":
if (!state.form[field]) {
errors[field] = "Please select an item";
invalidForm = true;
}
return;
case "quantity":
if (!state.form[field]?.length) {
errors[field] = "Please select a quantity";
invalidForm = true;
}
return;
case "unit":
if (!state.form[field]) {
errors[field] = "Please select a unit";
invalidForm = true;
}
return;
case "isIncoming":
if (!state.form[field]) {
errors[field] = "Please select an option";
invalidForm = true;
}
return;
}
});

if (invalidForm) {
dispatch({ type: "set_errors", errors });
return false;
}
dispatch({ type: "set_errors", errors });
return true;
};

const handleSubmit = async (e: any) => {
e.preventDefault();
const validated = validateForm();
if (!validated) return;
setIsLoading(true);
const data = {
quantity: Number(state.form.quantity),
Expand Down Expand Up @@ -240,6 +290,7 @@ export const AddInventoryForm = (props: any) => {
})}
optionValue={(inventory) => inventory.id}
optionLabel={(inventory) => inventory.name}
error={state.errors.id}
/>
</div>
<div>
Expand All @@ -256,7 +307,7 @@ export const AddInventoryForm = (props: any) => {
]}
optionValue={(inventory) => inventory.name}
optionLabel={(inventory) => inventory.name}
error={stockError}
error={stockError || state.errors.isIncoming}
/>
</div>
<div>
Expand All @@ -265,6 +316,7 @@ export const AddInventoryForm = (props: any) => {
name="quantity"
value={state.form.quantity}
onChange={handleChange}
error={state.errors.quantity}
/>
</div>
<div>
Expand All @@ -276,6 +328,7 @@ export const AddInventoryForm = (props: any) => {
options={currentUnit || []}
optionValue={(inventory) => inventory.id}
optionLabel={(inventory: any) => inventory.name}
error={state.errors.unit}
/>
</div>
</div>
Expand Down

0 comments on commit 0c03edc

Please sign in to comment.