I have a very simple problem in my react app. I wanted to submit only the date
and is_delicious
if the (toggle switch is_delicious
) is off. However how will i validate if the (toggle switch is_delicious
) is on and then all the 3 fields is required.
Check this codesandbox link
return (
<Formik
initialValues={{
is_delicious: false,
date: "",
food_name: ""
}}
validationSchema={foodSchema}
onSubmit={values => {
const formData = {
is_delicious: values.is_delicious === true ? 1 : 0,
food_name: values.food_name
};
console.log(formData);
}}
>
{({
values,
touched,
errors,
handleChange,
handleBlur,
setFieldValue,
handleSubmit
}) => (
<form onSubmit={handleSubmit}>
<TextField
name="date"
variant="outlined"
value={values.date}
onChange={handleChange}
onBlur={handleBlur}
helperText={touched.date ? errors.date : ""}
error={touched.date && Boolean(errors.date)}
label="Date"
type="date"
InputLabelProps={{
shrink: true
}}
fullWidth
/>
<FormControlLabel
name="is_delicious"
variant="outlined"
value={values.is_delicious}
checked={values.is_delicious}
onChange={handleChange}
onClick={() => getFoodValue(values.is_delicious)}
onBlur={handleBlur}
control={<Switch color="primary" />}
label="Is Delicious?"
labelPlacement="end"
style={{ display: "flex", justifyContent: "center" }}
/>
{showFood ? (
<TableContainer component={Paper}>
<Table className={classes.table} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Dessert (100g serving)</TableCell>
<TableCell align="right">Calories</TableCell>
<TableCell align="right">Fat (g)</TableCell>
<TableCell align="right">Carbs (g)</TableCell>
<TableCell align="right">Protein (g)</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map(row => {
const isItemSelected = isSelected(row);
return (
<TableRow
key={row.name}
hover
onClick={event => selectFood(event, row)}
selected={isItemSelected}
value={values.food_name}
>
<TableCell component="th" scope="row">
{row.name}
</TableCell>
<TableCell align="right">{row.calories}</TableCell>
<TableCell align="right">{row.fat}</TableCell>
<TableCell align="right">{row.carbs}</TableCell>
<TableCell align="right">{row.protein}</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
) : (
""
)}
<Button type="submit" color="primary" variant="contained">
Submit
</Button>
</form>
)}
</Formik>
);