I'm creating a form using yup and react hook form . the issue is the errors are triggered when sending the form but I want that the trigger will be when entering fields this is some of the code:
<Controller name="email"
control={control}
defaultValue=""
render={({field}) => (
<Input {...field} name={field.name} placeholder="email"/>
)}
/>
{errors.email && <span>{errors.email.message}</span>}
<Controller name="confirmation_email"
... />}
/>
email: yup.string().email(format_email).required(champs_obligatoire),
confirmation_email: yup.string()
.oneOf([yup.ref('email'), null], 'Emails must match').required(champs_obligatoire),
<form onSubmit={handleSubmit(onSubmit)}>
<MyForm errors={errors} control={control} t={t}/>
<Button type="submit" variant="contained">
Envoyer
</Button>
</form>
this code is from 3 files : the form and the services , thank you in advance for your help .
please I need a detailed explanation because I am new in react world.
Related
I am trying to use react form hook in my react form. and there i needed to use a field call 'status' which will have 0 or 1 value ie accept or reject. and as input i want to have two submit button with Accept And Reject.
I tried following but didnt worked
//this is schema
const schema = yup.object({
reply: yup.string().required("Reply"),
status: yup.number().oneOf([1, 2]),
});
// this is form controller
<Controller
name="status"
control={control}
render={({ field, fieldState }) => (
<Box display={'flex'} gap={2}>
<Button
color="error"
type="submit"
value={1}
variant='contained'
{...field}
>Accept</Button>
<Button
color="warning"
type="submit"
variant='contained'
value={2}
{...field}
>Reject</Button>
</Box>
)}
/>
First, I made a form validated with formik. After that, my team decided we would style with react-bootstrap. This library has a <Form> object, same as Formik. But it is not validating correctly. It either throws input fields as invalid all the time, thus putting its borders red, or as correct all the time.
I suspect it is a matter of combining libraries that work both with forms and have same-named components. I managed to make it work with original bootstrap library. But I still wanted to know why this happens and if it has some solution.
import React, {useState} from 'react';
import '../FormStyles.css';
import * as yup from "yup";
import { Formik, Form, ErrorMessage, Field } from 'formik';
const TestimonialForm = ({ testimonial = null }) => {
const initialValues = {
name: testimonial?.name || "",
description: testimonial?.description || "",
image: testimonial?.image || ""
};
const schema = yup.object().shape({
name: yup.string().min(4, "Name must be at least 4 characters long.").required("You have to provide a name."),
description: yup.string().required("You have to provide a description."),
image: yup.string()
.matches(
/\.(jpg|png)$/,
"We only support .png or .jpg format files."
)
.required("You have to provide an image.")
});
<Formik
initialValues= {initialValues}
validationSchema = {schema}
>
Here's the form with Formik components
{({}) => (
<div>
<Form className="form-container">
<Field
className="input-field"
type="text"
name="name"
placeholder="Testimonial title"/>
<ErrorMessage name="name" />
<Field
className="input-field"
type="file"
name="image"
placeholder="Testimonial image"/>
<ErrorMessage name="image" />
<button className="submit-btn" type="submit">Send</button>
</Form>
</div>
)}
</Formik>
Here's with react-bootstrap components (I only change the import values.) This are the ones that don't validate well.
{({touched, errors}) => (
<div>
<Form className="form-container" onSubmit={onSubmit}>
<Form.Group controlId="name">
<Form.Control
className="input-field"
type="text"
name="name"
isInvalid={name.touched && errors.name}
placeholder="Testimonial title"/>
<Form.Control.Feedback type="invalid">
{errors.name}
</Form.Control.Feedback>
</Form.Group>
<Form.Group controlId="image">
<Form.Control
className="input-field"
type="file"
name="image"
isInvalid={image.touched && errors.image}
/>
<Form.Control.Feedback type="invalid">
{errors.image}
</Form.Control.Feedback>
</Form.Group>
<button className="submit-btn" type="submit">Send</button>
{message && <div>{message}</div>}
</Form>
</div>
)}
</Formik>
I'm literally following their documentation and also tried the code from an article on github. I have the most recent version installed. Still not working. So frustateeeeeed.
const { control, handleSubmit } = useForm()
This is the component I return:
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="lastName"
control={control}
defaultValue=""
render={({ field, fieldState }) => (
<TextField
label="Last Name"
variant="filled"
value={field.value}
onChange={field.onChange}
error={!!fieldState.error}
helperText={fieldState.error ? fieldState.error.message : null}
/>
)}
rules={{ required: 'Last name required' }}
<Button type="submit" disabled={!stripe} buttonText="Pay"></Button>
</form>
It simply keeps giving the error that field.value, field.onchange, fieldState.error are undefined. I tried destructuring too. Doesn't work either.
Here is a working example: https://codesandbox.io/s/ancient-worker-mdqx3
I recommend passing the ref as well.
Hey I'm currently working on validation using customized Antd inputs and React Hook Form.
Currently I have problem with validating fields for URLs (single url and image one) with regex.
I've checked both of regex and they are working
Generally I can't submit the form with correct data, the problem happens within the validation using regex
The form part
<Controller
as={
<InputField
label="URL"
name="url"
placeholder="Enter URL"
error={errors.url}
errorText="URL Error"
/>
}
control={control}
type="text"
name="url"
defaultValue=""
rules={{
validate: (value) => {
return INPUT.urlPattern.test(value);
}
}}
/>
<Controller
as={
<InputField
label="Image Url"
name="imageUrl"
placeholder="enter ImageURL"
error={errors.imageUrl}
errorText="Error on imageUrl"
/>
}
control={control}
type="text"
name="imageUrl"
defaultValue=""
rules={{
validate: (value) => {
return INPUT.imageURLPattern.test(value);
}
}}
/>
Custom antd input component render function
return (
<>
<label className="label" htmlFor={name}>
{label}
</label>
<Styled.Input
placeholder={placeholder}
maxLength={maxLength}
value={value}
onChange={handleInputCounter}
{...(counter
? {
suffix: (
<Styled.WordCounter>
{counterValue} / {maxLength}
</Styled.WordCounter>
)
}
: {})}
/>
{error && <p className="error">{errorText}</p>}
</>
);
I've prepared little demo on codesandbox
https://codesandbox.io/s/react-hook-form-validate-antd-gyhnh?file=/src/EntryForm.tsx
I've been working with React for a while, and decided to try out react-hook. I'm trying to make a simple form with some simple validation, but it seems like the validation does not apply to bootstrap components. For the 'regular' input, it works fine, but for the form.control it's not working(The validation is skipped). Saw one solution where you wrap the componenet in a controller, as shown bellow, but i got the same result. Any ideas?
Thanks.
function Example(){
const { register, handleSubmit, control, errors } = useForm();
const onSubmit = (data:any) => {
console.log(data)
}
return(
<Form onSubmit={handleSubmit(onSubmit)}>
<Form.Label column>Name</Form.Label>
<Controller as={<Form.Control/>} name="firstName" control={control} ref={register({required: true})} defaultValue="" />
{errors.firstName && <p>This is required</p>}
<input name="lastName" className="form-control" ref={register({required: true})} />
{errors.lastName && <p>This is required</p>}
<input type="submit" ref={register({required: true})}/>
</Form>
)
}