Skip to content

Commit 5f26c94

Browse files
authored
Merge pull request #551 from janong24/contactDataValidation
Fixed contact form submitting when faulty data is entered
2 parents 9847db9 + 5c7a058 commit 5f26c94

File tree

2 files changed

+199
-210
lines changed

2 files changed

+199
-210
lines changed
Lines changed: 112 additions & 116 deletions
Original file line numberDiff line numberDiff line change
@@ -1,176 +1,172 @@
1-
'use client';
2-
import FormLabel from '@/app/components/FormLabel';
3-
import Custom403 from '@/app/pages/403';
4-
import { useFormik } from 'formik';
5-
import { useRouter } from 'next/navigation';
6-
import { useEffect, useState } from 'react';
7-
import Button from '../../components/Button';
8-
import Header from '../../components/Header';
9-
import Input from '../../components/Input';
10-
import { useAuth } from '../../contexts/AuthContext';
11-
import { getSpeedDial, updateSpeedDial } from '../../http/speedDialAPI';
1+
"use client";
2+
import FormLabel from "@/app/components/FormLabel";
3+
import Custom403 from "@/app/pages/403";
4+
import { useFormik } from "formik";
5+
import { useRouter } from "next/navigation";
6+
import { useEffect, useState } from "react";
7+
import Button from "../../components/Button";
8+
import Header from "../../components/Header";
9+
import Input from "../../components/Input";
10+
import { useAuth } from "../../contexts/AuthContext";
11+
import { getSpeedDial, updateSpeedDial } from "../../http/speedDialAPI";
1212

13-
14-
export default function UpdateContactPage( {params: { updateContacts } } : { params: { updateContacts: string }} ) {
15-
const logger = require('../../../logger');
13+
export default function UpdateContactPage({
14+
params: { updateContacts },
15+
}: {
16+
params: { updateContacts: string };
17+
}) {
18+
const logger = require("../../../logger");
1619
const router = useRouter();
1720
const { user } = useAuth();
18-
const [contacts, setContacts] = useState<any>(null);
19-
21+
const [contacts, setContacts] = useState<any>(null);
22+
2023
async function fetchContact() {
2124
try {
22-
const userId = user?.uid || '';
23-
const result = await getSpeedDial(updateContacts);
24-
logger.info('Speed dial entry retrieved:', result);
25+
const userId = user?.uid || "";
26+
const result = await getSpeedDial(updateContacts);
27+
logger.info("Speed dial entry retrieved:", result);
2528
setContacts(result.data);
2629
} catch (error) {
27-
logger.error('Error retrieving speed dial entry:', error);
30+
logger.error("Error retrieving speed dial entry:", error);
2831
}
2932
}
3033

31-
useEffect(() => {
34+
useEffect(() => {
3235
if (!user) {
33-
router.push('/login')
34-
logger.warn('User not found.')
35-
alert('User not found.');
36-
}
36+
router.push("/login");
37+
logger.warn("User not found.");
38+
alert("User not found.");
39+
}
3740
if (user) {
3841
setTimeout(() => {
3942
fetchContact();
40-
},1000);
43+
}, 1000);
4144
}
4245
}, []);
43-
46+
4447
// if (!user) {
4548
// return <div><Custom403/></div>
4649
// }
4750

48-
useEffect(() =>{
49-
const { setValues } = formik;
51+
useEffect(() => {
52+
const { setValues } = formik;
5053
setValues({
51-
contactName: contacts?.contactName || '',
52-
phone: contacts?.contactNumber || '',
53-
})
54-
}, [contacts])
54+
contactName: contacts?.contactName || "",
55+
phone: contacts?.contactNumber || "",
56+
});
57+
}, [contacts]);
5558

5659
const formik = useFormik({
5760
initialValues: {
58-
contactName: '', // Initialize the form fields with empty values
59-
phone: '',
61+
contactName: "", // Initialize the form fields with empty values
62+
phone: "",
6063
},
6164

6265
onSubmit: async (values) => {
6366
try {
64-
const userId = user?.uid || '';
67+
const userId = user?.uid || "";
6568
const data = {
6669
contactName: values.contactName,
6770
contactNumber: values.phone,
6871
};
69-
updateSpeedDial(updateContacts, data)
70-
.then(result => {
71-
router.push('/contacts');
72-
})
72+
updateSpeedDial(updateContacts, data).then((result) => {
73+
router.push("/contacts");
74+
});
7375
} catch (error) {
74-
logger.error('Error updating speed dial entry:', error);
76+
logger.error("Error updating speed dial entry:", error);
7577
}
7678
},
7779

7880
validate: (values) => {
7981
let errors: {
80-
contactName?:string;
82+
contactName?: string;
8183
phone?: string;
8284
} = {};
8385
if (!values.contactName) {
84-
errors.contactName = 'Contact Name Required';
85-
} else if (
86-
!/^[^0-9 ][^\d]*[^0-9 ]$/i.test(values.contactName)
87-
){
88-
errors.contactName = 'Names cannot contain numbers and must not begin or end with a space.';
86+
errors.contactName = "Contact Name Required";
87+
} else if (!/^[^0-9 ][^\d]*[^0-9 ]$/i.test(values.contactName)) {
88+
errors.contactName =
89+
"Names cannot contain numbers and must not begin or end with a space.";
8990
}
9091
if (!values.phone) {
91-
errors.phone = 'Phone Number Required';
92+
errors.phone = "Phone Number Required";
9293
} else if (!/^[0-9]{10}$/i.test(values.phone)) {
93-
errors.phone = 'Please enter a 10 digit number';
94+
errors.phone = "Please enter a 10 digit number";
9495
}
9596

9697
return errors;
9798
},
9899
});
99100

100-
101101
return (
102102
<div className="bg-eggshell min-h-screen flex flex-col">
103-
<span className="flex items-baseline font-bold text-darkgrey text-[24px] mx-4 mt-4 mb-4">
104-
<button onClick={() => router.push('/contacts')}>
105-
<Header headerText="Update Contact"></Header>
106-
</button>
107-
</span>
103+
<span className="flex items-baseline font-bold text-darkgrey text-[24px] mx-4 mt-4 mb-4">
104+
<button onClick={() => router.push("/contacts")}>
105+
<Header headerText="Update Contact"></Header>
106+
</button>
107+
</span>
108108
<form
109-
className="rounded-3xl bg-white flex flex-col mb-8 w-full md:max-w-[800px] md:min-h-[550px] p-8 shadow-[0_32px_64px_0_rgba(44,39,56,0.08),0_16px_32px_0_rgba(44,39,56,0.04)]"
110-
onSubmit={formik.handleSubmit}
109+
className="rounded-3xl bg-white flex flex-col mb-8 w-full md:max-w-[800px] md:min-h-[550px] p-8 shadow-[0_32px_64px_0_rgba(44,39,56,0.08),0_16px_32px_0_rgba(44,39,56,0.04)]"
110+
onSubmit={formik.handleSubmit}
111111
>
112-
113-
<div className="mt-3">
114-
<FormLabel htmlFor={ 'contactName' } label={'Contact Name'}></FormLabel>
115-
<Input
116-
name="contactName"
117-
id="contactName"
118-
type="text"
119-
style={{ width: '100%' }}
120-
onChange={formik.handleChange}
121-
value={formik.values.contactName}
122-
onBlur={formik.handleBlur}
123-
/>
124-
{formik.touched.contactName && formik.errors.contactName && (
125-
<p className="text-[16px] text-red font-sans">
126-
{formik.errors.contactName}
127-
</p>
128-
)}
129-
</div>
112+
<div className="mt-3">
113+
<FormLabel htmlFor={"contactName"} label={"Contact Name"}></FormLabel>
114+
<Input
115+
name="contactName"
116+
id="contactName"
117+
type="text"
118+
style={{ width: "100%" }}
119+
onChange={formik.handleChange}
120+
value={formik.values.contactName}
121+
onBlur={formik.handleBlur}
122+
/>
123+
{formik.touched.contactName && formik.errors.contactName && (
124+
<p className="text-[16px] text-red font-sans">
125+
{formik.errors.contactName}
126+
</p>
127+
)}
128+
</div>
130129

131-
<div className="mt-3">
132-
<FormLabel htmlFor={ 'phone' } label={'Phone Number'}></FormLabel>
133-
<Input
134-
name="phone"
135-
id="phone"
136-
type="text"
137-
style={{ width: '100%' }}
138-
onChange={formik.handleChange}
139-
value={formik.values.phone}
140-
onBlur={formik.handleBlur}
141-
/>
142-
{formik.touched.phone && formik.errors.phone && (
143-
<p className="text-[16px] text-red font-sans">
144-
{formik.errors.phone}
145-
</p>
146-
)}
147-
</div>
148-
149-
150-
<div className='mt-10 pb-4 self-center'>
151-
<div className="mt-5 mb-5 space-x-2">
152-
<Button
153-
type="button"
154-
text="Cancel"
155-
style={{ width: '140px', backgroundColor: 'var(--Red, #FF7171)' }}
156-
onClick={() => router.push("/contacts")}
157-
/>
130+
<div className="mt-3">
131+
<FormLabel htmlFor={"phone"} label={"Phone Number"}></FormLabel>
132+
<Input
133+
name="phone"
134+
id="phone"
135+
type="text"
136+
style={{ width: "100%" }}
137+
onChange={formik.handleChange}
138+
value={formik.values.phone}
139+
onBlur={formik.handleBlur}
140+
/>
141+
{formik.touched.phone && formik.errors.phone && (
142+
<p className="text-[16px] text-red font-sans">
143+
{formik.errors.phone}
144+
</p>
145+
)}
146+
</div>
158147

148+
<div className="mt-10 pb-4 self-center">
149+
<div className="mt-5 mb-5 space-x-2">
150+
<Button
151+
type="button"
152+
text="Cancel"
153+
style={{ width: "140px", backgroundColor: "var(--Red, #FF7171)" }}
154+
onClick={() => router.push("/contacts")}
155+
/>
159156

160-
<Button
161-
type="submit"
162-
text="Submit"
163-
disabled={
164-
!(formik.isValid && formik.dirty) || // Check if the form is valid and dirty
165-
!formik.values.contactName || // Check if contact name is missing or empty
166-
!formik.values.phone // Check if phone is missing or empty
167-
}
168-
style={{ width: '140px', textAlign: 'center' }}
169-
onClick={() => router.push("/contacts")}
170-
/>
157+
<Button
158+
type="submit"
159+
text="Submit"
160+
disabled={
161+
!(formik.isValid && formik.dirty) || // Check if the form is valid and dirty
162+
!formik.values.contactName || // Check if contact name is missing or empty
163+
!formik.values.phone // Check if phone is missing or empty
164+
}
165+
style={{ width: "140px", textAlign: "center" }}
166+
/>
167+
</div>
171168
</div>
172-
</div>
173-
</form>
169+
</form>
174170
</div>
175171
);
176-
}
172+
}

0 commit comments

Comments
 (0)