i am creating a form, instead of using manual validations, i read using the validations provided by react-hook-form and yup are more efficient and can save a lot of time , so on the website i follow the instruction, i was getting the error 'path.split is not defined', now searching on the web , i am using this code, which doesn't give any error by also not printing the validation on page, however when i submit it does shows up on my console
const { fields, handleChange,register,handleSubmit,errors } = useFormFields({
productName: '',
category: [],
availablity: [],
itemOutOfStock: false,
Price: 0,
Tax: '0',
productDescription: '',image:"",
...initialFormData // Merge with provided initialFormData if available }, onFormDataChange);
const Submit = async () => {
try {
const selectedCategory = fields.category ? [fields.category] : [];
const selectedAvailablity = fields.availablity ? [fields.availablity] : [];
const formDataWithMappedCategory = {...fields,category: selectedCategory,
availablity:selectedAvailablity,};
await validationSchema.validate(formDataWithMappedCategory, { abortEarly: false });
await onNext();
}
catch (err) {
console.log('Validation errors:', err.errors);
console.log(err);
} };
//form <form onSubmit={handleSubmit(Submit)}>
<div>
<Grid container spacing={2} sx={{ width: '1000px' }}>
<Grid item xs={12} sm={6}>
<FormControl fullWidth>
<label>Product Name <span style={{ color: 'red' }}>*</span>
</label>
<TextField
fullWidth
label="Product Name"
name="productName"
value={fields.productName}
onChange={handleChange}
inputRef={register('productName', { required: true })}
error={!!errors.productName}
helperText={errors.productName?.message}/>
{errors.productName && (<p>{errors.productName.message}</p>)} </FormControl>
</Grid>
//validations
import * as yup from 'yup';
const validationSchema = yup.object().shape({
productName: yup.string().required('Product name is required'),
category: yup.array().min(1, 'Please select at least one category').required('Please select at least one category'),
availablity: yup.array().min(1, 'Please select at least one availability').required('Please select at least one availability'),
Price: yup.number().min(0, 'Price must be greater than or equal to 0'),
Tax: yup.number().min(0, 'Tax must be greater than or equal to 0'),
productDescription: yup.string().required("Product Description is required"),
image: yup
.mixed()
.test('fileSize', 'File size is too large', (value) => {
return !value || value.size <= 1024 * 1024 * 2; // 2 MB
})
.test('fileType', 'Unsupported file type', (value) => {
return !value || ['image/jpeg', 'image/png', 'image/gif'].includes(value.type);
}).required(),
}).required()
// ...
export default validationSchema;```