forked from bloominstituteoftechnology/W_S7_Challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathForm.js
146 lines (131 loc) · 5.13 KB
/
Form.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import React, { useEffect, useState } from 'react'
import * as Yup from 'yup';
// 👇 Here are the validation errors you will use with Yup.
const validationErrors = {
fullNameTooShort: 'full name must be at least 3 characters',
fullNameTooLong: 'full name must be at most 20 characters',
sizeIncorrect: 'size must be S or M or L'
}
const isFormValid = Yup.object().shape({
fullName: Yup.string()
.min(3, validationErrors.fullNameTooShort)
.max(20, validationErrors.fullNameTooLong)
.required('Full name is required'),
size: Yup.string()
.oneOf(['S', 'M', 'L'], validationErrors.sizeIncorrect)
.required('Size is required'),
});
const toppings = [
{ topping_id: '1', text: 'Pepperoni' },
{ topping_id: '2', text: 'Green Peppers' },
{ topping_id: '3', text: 'Pineapple' },
{ topping_id: '4', text: 'Mushrooms' },
{ topping_id: '5', text: 'Ham' },
]
export default function Form() {
const [formState, setFormState] = useState({
fullName: '',
size: '',
toppings: []
});
const [errorState, setErrorState] = useState({
fullName: '',
size: '',
});
const [submitEnabled, setSubmitEnabled] = useState(false);
const [formSuccess, setFormSuccess] = useState('');
const [formError, setFormError] = useState('');
const [sizeChanged, setSizeChanged] = useState(false); // Track if size has been changed
useEffect(() => {
// Validate form on state change
const validateForm = async () => {
try {
await isFormValid.validate(formState, { abortEarly: false });
setErrorState({ fullName: '', size: '' });
setSubmitEnabled(true);
} catch (err) {
const errors = {};
err.inner.forEach(error => {
errors[error.path] = error.message;
});
setErrorState(errors);
setSubmitEnabled(false);
}
};
validateForm();
}, [formState]);
const handleSubmit = (e) => {
e.preventDefault();
if (submitEnabled) {
setFormSuccess(`Thank you for your order, ${formState.fullName}! Your ${formState.size === 'S' ? 'Small' : formState.size === 'M' ? 'Medium' : 'Large'} pizza with ${formState.toppings.length > 0 ? formState.toppings.length + ' toppings' : 'no toppings'} is on the way.`);
setFormError('');
// Reset form state and error state
setFormState({ fullName: '', size: '', toppings: [] }); // Reset size to empty string
setErrorState({ fullName: '', size: '' }); // Reset error state
setSizeChanged(false); // Reset size changed state
} else {
setFormError('Please fix the errors before submitting.');
}
};
return (
<form onSubmit={handleSubmit}>
<h2>Order Your Pizza</h2>
{formSuccess && <div className='success'>{formSuccess}</div>}
{formError && <div className='failure'>{formError}</div>}
<div className="input-group">
<div>
<label htmlFor="fullName">Full Name</label><br />
<input placeholder="Type full name" id="fullName" type="text" value={formState.fullName}
onChange={(e) => {
setFormState({ ...formState, fullName: e.target.value.trim() }); // Trim whitespace
// No need to track touched state
}}
/>
</div>
{formState.fullName && errorState.fullName && <div className='error'>{errorState.fullName}</div>}
</div>
<div className="input-group">
<div>
<label htmlFor="size">Size</label><br />
<select id="size" value={formState.size} onChange={(e) => {
const newSize = e.target.value;
setFormState({ ...formState, size: newSize });
setSizeChanged(true); // Mark size as changed
// Show error if changing from a valid size to empty
if (newSize === '') {
setErrorState((prev) => ({ ...prev, size: validationErrors.sizeIncorrect }));
} else {
setErrorState((prev) => ({ ...prev, size: '' })); // Clear error if valid size is selected
}
}}>
<option value="">----Choose Size----</option>
<option value="S">Small</option>
<option value="M">Medium</option>
<option value="L">Large</option>
</select>
</div>
{sizeChanged && formState.size === '' && errorState.size && <div className='error'>{errorState.size}</div>}
</div>
<div className="input-group">
{toppings.map((topping) => (
<label key={topping.topping_id}>
<input
name={topping.text}
type="checkbox"
checked={formState.toppings.includes(topping.topping_id)}
onChange={(e) => {
if (e.target.checked) {
setFormState({ ...formState, toppings: [...formState.toppings, topping.topping_id] });
} else {
setFormState({ ...formState, toppings: formState.toppings.filter(t => t !== topping.topping_id) });
}
}}
/>
{topping.text}<br />
</label>
))}
</div>
<input type="submit" disabled={!submitEnabled} />
</form>
)
}