formik rendering an element when input field is clicked in react? - reactjs

I am trying to make a simple login form i want to render an element when an input field is clicked . I have done this in normal react form by rendering an element by changing the value of a boolean variable to true and when the input is written if the user touch somewhere else then the element disapears . kind of toggle thing . but i don't know hoe to do this in formik. my code looks like this.
import React from "react";
import { Formik } from "formik";
import * as EmailValidator from "email-validator";
import * as Yup from "yup";
const ValidatedLoginForm = () => (
<Formik
initialValues={{ email: "", password: "" }}
onSubmit={(values, { setSubmitting }) => {
console.log(values);
console.log("hello there ");
}}
validationSchema={Yup.object().shape({
email: Yup.string()
.email()
.required("Required"),
password: Yup.string()
.required("No password provided.")
.min(8, "Password is too short - should be 8 chars minimum.")
.matches(/(?=.*[0-9])/, "Password must contain a number.")
})}>
{props => {
const {
values,
touched,
errors,
isSubmitting,
handleChange,
handleBlur,
handleSubmit
} = props;
return (
<div className="container">
<div className="row">
<form onSubmit={handleSubmit}>
<br />
<input
name="email"
type="text"
placeholder="Enter your email"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
className={errors.email && touched.email && "error"}
/>
<br />
<br />
{errors.email && touched.email && (
<div className="input-feedback">{errors.email}</div>
)}
<br />
<input
name="password"
type="password"
placeholder="Enter your password"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
className={errors.password && touched.password && "error"}
/> <br />
<br />
{errors.password && touched.password && (
<div className="input-feedback">{errors.password}</div>
)}
<button type="submit" disabled={isSubmitting}>
Login
</button>
</form>
</div>
<div className="row">
<button className="btn btn-default">Value</button>
</div>
</div>
);
}}

Maybe this will help you. Try to add function to onBlur prop then handle handleBlur function.
onBlur={(e) => {
handleBlur(e);
// here handle component showing
}}

Related

React Formik submission

I have an authorization and validation form for registration. I need to to make my form available for click events at my button. At first i added the resetform function in order to notice how my form actually works but after each click nothing happens.
import { Button, TextField } from "#mui/material";
import * as yup from "yup";
import { Formik } from "formik";
export const RegistrationForm = () => {
const validationSchema = yup.object().shape({
name: yup
.string()
.typeError("Должно быть строкой")
.required("Обязательно")
.matches(/^[аА-яЯ\s]+$/, "Имя должно состоять из русских букв"),
secondName: yup
.string()
.typeError("Должно быть строкой")
.required("Обязательно")
.matches(/^[аА-яЯ\s]+$/, "Фамилия должна состоять из русских букв"),
login: yup
.string()
.typeError("Должно быть строкой")
.required("Обязательно"),
password: yup
.string()
.typeError("Должно быть строкой")
.required("Обязательно"),
confirmPassword: yup
.string()
.oneOf([yup.ref("password")], "Пароли не совпадают")
.required("Обязательно"),
email: yup.string().email("Введите верный email").required("Обязательно"),
confirmEmail: yup
.string()
.email("Введите верный email")
.oneOf([yup.ref("email")], "Email не совпадают")
.required("Обязательно"),
});
return (
<>
<header>
<div className="head-btns">
<Button variant="outlined">Зарегистрироваться</Button>
<Button variant="outlined">Авторизоваться</Button>
</div>
</header>
<Formik
initialValues={{
name: "",
secondName: "",
login: "",
password: "",
confirmPassword: "",
email: "",
confirmEmail: "",
}}
validateOnBlur
onSubmit={({ resetForm }) => resetForm()}
validationSchema={validationSchema}
>
{({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isValid,
dirty,
}) => (
<div className="register">
<TextField
id="outlined-basic"
label="Имя"
variant="outlined"
className="field"
name={"name"}
onChange={handleChange}
onBlur={handleBlur}
value={values.name}
/>
{touched.name && errors.name && (
<p className={"error"}>{errors.name}</p>
)}
<TextField
id="outlined-basic"
label="Фамилия"
variant="outlined"
className="field"
name={"secondName"}
onChange={handleChange}
onBlur={handleBlur}
value={values.secondName}
/>
{touched.secondName && errors.secondName && (
<p className={"error"}>{errors.secondName}</p>
)}
<TextField
id="outlined-basic"
label="Логин"
variant="outlined"
className="field"
name={"login"}
onChange={handleChange}
onBlur={handleBlur}
value={values.login}
/>
{touched.login && errors.login && (
<p className={"error"}>{errors.login}</p>
)}
<TextField
type="password"
id="outlined-basic"
label="Пароль"
variant="outlined"
className="field"
name={"password"}
onChange={handleChange}
onBlur={handleBlur}
value={values.password}
/>
{touched.password && errors.password && (
<p className={"error"}>{errors.password}</p>
)}
<TextField
type="password"
id="outlined-basic"
label="Подтвердите пароль"
variant="outlined"
className="field"
name={"confirmPassword"}
onChange={handleChange}
onBlur={handleBlur}
value={values.confirmPassword}
/>
{touched.confirmPassword && errors.confirmPassword && (
<p className={"error"}>{errors.confirmPassword}</p>
)}
<TextField
id="outlined-basic"
label="Email"
variant="outlined"
className="field"
name={"email"}
onChange={handleChange}
onBlur={handleBlur}
value={values.email}
/>
{touched.email && errors.email && (
<p className={"error"}>{errors.email}</p>
)}
<TextField
id="outlined-basic"
label="Подтвердите Email"
variant="outlined"
className="field"
name={"confirmEmail"}
onChange={handleChange}
onBlur={handleBlur}
value={values.confirmEmail}
/>
{touched.confirmEmail && errors.confirmEmail && (
<p className={"error"}>{errors.confirmEmail}</p>
)}
<Button
onClick={handleSubmit}
disabled={!isValid || !dirty}
type="submit"
variant="contained"
className="btn"
>
Зарегистрироваться
</Button>
</div>
)}
</Formik>
</>
);
};
I clicked the button and nothing happens but it should reset all inputs after this action
The onSubmit prop given to the <Formik /> component should be like this:
<Formik
onSubmit={(values, { resetForm }) => resetForm()}
validationSchema={validationSchema}
>
</Formik>
Formik options are passed to the second parameter of the submit handler.
And you don't need to explicitly give your Button onClick handler with type="submit" if you define your form in the HTML form tag.
<Formik
onSubmit={(values, { resetForm }) => resetForm()}
validationSchema={validationSchema}
>
{({ handleSubmit }) => (
<form onSubmit={handleSubmit>
{/* your form */}
<Button
type="submit" // giving type submit to a button enclosed in a form will automatically call handleSubmit method
>
Submit
</Button>
</form>
)}
</Formik>

Yup Was Not Working With Formik and also not provide any type of error

Yup Validation Not Working I Also tried Like This import Yup from 'yup' But Still Not Working.., when I create a simple validate Function without YUP it was worked fine. but when I use YUP that time Validation Not Work.
Added Form Component
import React from 'react';
import { useFormik } from 'formik';
import * as Yup from 'yup';
const initialValues = {
name : "",
surname : "",
address : ""
}
const validateSchema = Yup.object({
name: Yup.string().required('This Field is Required'),
surname: Yup.string().required('This Field is Required'),
address: Yup.string().required('This Field is Required')
});
const onSubmit = values =>{
console.log('FormData->',values);
}
function Form() {
const formik = useFormik({
initialValues ,
onSubmit ,
validateSchema
})
return (
<div className="container x col-md-4 col-md-offset-4" >
<form onSubmit={formik.handleSubmit} >
<div className="form-group">
<input autoComplete="off" onBlur={formik.handleBlur} onChange={formik.handleChange}
value={formik.values.name} name="name" className="name form-control-lg" placeholder="Enter A Name" />
<small>
{formik.touched.name && formik.errors.name ? <div className="error"> {formik.errors.name} </div> : null}
</small>
</div>
<div className="form-group">
<input autoComplete="off" onBlur={formik.handleBlur} onChange={formik.handleChange}
value={formik.values.surname} name="surname" className="surname form-control-lg" placeholder="Enter A Surname" />
<small> { formik.touched.surname && formik.errors.surname ? <div className="error"> {formik.errors.surname} </div> : null} </small>
</div>
<div className="form-group">
<input autoComplete="off" onBlur={formik.handleBlur} onChange={formik.handleChange} value={formik.values.address}
name="address" className="address form-control-lg" placeholder="Enter A Address" />
<small> {formik.touched.address && formik.errors.address ? <div className="error"> {formik.errors.address} </div> : null} </small>
</div>
<button className="btn btn-danger" >Submit</button>
</form>
</div>
)
}
export default Form;
The valid option here is validationSchema not validateSchema. Just set the right one:
const validationSchema = Yup.object({
// ...
});
useFormik({
// ...
validationSchema
})
To use formik and yup, first you have you do npm install yup and npm install formik. if your yarn user then do yarn add formik and yarn add yup.
after that follow this code.
import {Formik} from 'formik';
import * as yup from 'yup';
//functional component am using
export const Auth = () => {
const initialFormValue ={
email: '',password: '',};
const SignInSchema = yup.object().shape({
email: yup.string().email('Invalid Email').required('Email is Required'),
password: yup.string().min(5, 'Too Short').required('Password is Required'),
})
<Formik initialValues={initialFormValue} validationSchema={SignInSchema}
onSubmit={values => console.log(values)}>
{({values, errors, touched, handleChange, handleBlur,
handleSubmit,isSubmitting,
isValid}) => (
<>
<input name='email' type='email' handleChange={handleChange} value=
{values.email} onBlur={handleBlur} label='Email' />
{errors.email && touched.email ? (<Error>{errors.email}</Error>): null}
<input name='password' type='password' handleChange={handleChange} value=
{values.password} onBlur={handleBlur} label='Password' />
{errors.password && touched.password ? (<Error>{errors.password}</Error>):
null}
<button onClick={handleSubmit} type="submit">Send</button>
</>
) }
</Formik>
)}
its not necessary for you to define initial value outside you can do inside formik too <Formik initialValues={email: '', password: ''}> </Formik>
i hope this will help you thank you.

React + Formik + Yup async validation

Formik + yup
validation with .test() triggers on change on every field
example:
i have a validation schema:
const schemaValidation = yup.object().shape({
name: yup.string().required(),
email: yup.string().email().required()
.test( // it runs even if previous validation failed!
'checkEmailExists', 'email already taken.',
// it triggers on every onBlur
email => { console.log('email registration runs') return Promise.resolve(true)}
),
other: yup.string().required()
.test(
'checkOthers', 'error',
val => {console.log('other validation runs'); return Promise.resolve(true)}
)
})
render function on my react component looks like:
...
render () {
return(
<Formik
validateOnChange={false}
validateOnBlur={true}
initialValues={{
name: '',
email: '',
other: ''
}}
validationSchema={schemaValidation}
onSubmit={this.handleSubmit}
>
{(props) => (
<Form>
<div className="field">
<Field className="input" type="email" name="email" placeholder="Email" />
<ErrorMessage name="email" />
</div>
<div className="field">
<Field className="input" type="text" name="name" placeholder="Name"/>
<ErrorMessage name="name" />
</div>
<div className="field">
<Field className="input" type="text" name="other" placeholder="Other"/>
<ErrorMessage name="other" />
</div>
<button type="submit">Submit</button>
</Form>
)}
</Formik>
)
so after every single field changed I receive messages from all .test() validators in console:
email registration runs
other validation runs
versions:
react: 16.13.1
formik: 2.1.4
yup: 0.28.4
By default formik validates after change, blur and submit events. Your code disables validation after change events with validateOnChange={false}. In order to only validate on submit events, try setting validateOnBlur to false too.
https://jaredpalmer.com/formik/docs/guides/validation#when-does-validation-run
https://jaredpalmer.com/formik/docs/api/formik#validateonblur-boolean
Hello everyone in 2022,
I understand a lot of formik has changed over the years - but thought I share a relevant solution that's using touched property, feel free to peek at https://codesandbox.io/s/stack-overflow-54204827-llvkzc.
And also shared for another StackOverflow question here, React Native Form Validation.
In summary, it's basically used like below (with yup outside of this snippet), to decide whether to show (if any) input validation errors:
<Formik
initialValues={{
email: "",
password: ""
}}
validationSchema={LoginSchemaA}
onSubmit={(
values: Values,
{ setSubmitting }: FormikHelpers<Values>
) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
setSubmitting(false);
}, 500);
}}
>
{({ errors, touched }) => (
<Form>
<label htmlFor="email">Email</label>
<Field
id="email"
name="email"
placeholder="john.doe#email.com"
type="email"
/>
{errors.email && touched.email ? (
<div style={{ color: "red" }}>{errors.email}</div>
) : null}
<label htmlFor="password">Password</label>
<Field id="password" name="password" type="password" />
{errors.password && touched.password ? (
<div style={{ color: "red" }}>{errors.password}</div>
) : null}
<button type="submit">Submit</button>
</Form>
)}
</Formik>
And as package.json reference, below are the defined versions:
"dependencies": {
...
"formik": "2.2.9",
...
"yup": "0.32.11"
},
Hope this helps for those on these mentioned formik and yup versions above!

REACT.JS + FORMIK input field proble,

this is my first ever stack overflow question. I am trying to build a log-in page (making a full stack app with node express mongodb mongoose) and front end being REACT. I am running into an issue where the input field css does not register until I click into the input field and click out. I am using Formik to develop my form. I have two questions essentially: How can I fix this issue and how can I do an API call to my backend server which is running on localhost:3003. Here is the code:
import React from "react";
import "../App.css";
import { Formik } from "formik";
import * as EmailValidator from "email-validator";
import * as Yup from "yup";
const ValidatedLoginForm = () => (
<Formik
initialValues={{ email: "", password: "" }}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
console.log("Logging in", values);
setSubmitting(false);
}, 500);
}}
validationSchema={Yup.object().shape({
email: Yup.string()
.email()
.required("Required"),
password: Yup.string()
.required("No password provided.")
.min(8, "Password is too short - should be 8 chars minimum.")
.matches(/(?=.*[0-9])/, "Password must contain a number.")
})}
>
{props => {
const {
values,
touched,
errors,
isSubmitting,
handleChange,
handleBlur,
handleSubmit
} = props;
return (
<div className="FormCenter">
<form onSubmit={handleSubmit} className="FormFields">
<div className="FormField">
<label htmlFor="email" className="FormField__Label">
Email
</label>
<input
name="email"
type="text"
placeholder="Enter your email"
value={values.email}
onBlur={handleBlur}
onChange={handleChange}
className={
errors.email && touched.email && "error" && "FormField__Input"
}
/>
{errors.email && touched.email && (
<div className="input-feedback">{errors.email}</div>
)}
</div>
<div className="FormField">
<label htmlFor="email" className="FormField__Label">
Password
</label>
<input
name="password"
type="password"
placeholder="Enter your password"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
className={
errors.password &&
touched.password &&
"error" &&
"FormField__Input"
}
/>
{errors.password && touched.password && (
<div className="input-feedback">{errors.password}</div>
)}
</div>
<div className="FormField">
<button
type="submit"
className="FormField__Button mr-20"
onChange
>
Login
</button>
</div>
</form>
</div>
);
}}
</Formik>
);
export default ValidatedLoginForm;
This looks like a normal behaviour to me. The validation in the form will get triggered when ,
when you submit the form
when the field is touched . Becoz of this you are seeing the error message being displayed when you switch between the fields without entering the values .
You should be firing the api call from the onSubmit, were you will get to access all the form values . I would suggest you to use fetch api . https://developer.mozilla.org/en/docs/Web/API/Fetch_API
Just make your onSubmit as a asyn method and fire your api call inside it .

How to use useState hook in formik forms

I am using formik form and to get make a modal on this form how can i use useState hook ?
FormReq = ({ values, errors, touched, handleChange, isSubmitting, handleBlur }) =>
(
<>
<div className="container">
<Modal email={values.email} password={values.password}/>
</div>
<Form>
<div className="container">
<div className="form">
<Field type="email" name="email" placeholder="Email" onChange={handleChange} onBlur={handleBlur} className="inputField"/>
<Field type="password" name="password" placeholder="Password" onChange={handleChange} className="inputField"/>
<span className="buttonsubmit">
<button disabled={isSubmitting}>Submit</button>
</span>
</div>
</div>
<div className="container errors">
{ touched.email && errors.email && <p>{errors.email}</p> }
{ touched.password && errors.password && <p>{errors.password}</p> }
</div>
</Form>
</>
)
const ContactUs = withFormik({
mapPropsToValues({ email, password}){
return{
email: email || '',
password: password || ''
}
},
validationSchema: Yup.object().shape({
email: Yup.string().email('Email not valid').required('Email is required'),
password: Yup.string().min(9, 'Password must be 9 characters or longer').required('Password is required')
}),
handleSubmit(values, { resetForm }){
console.log(values);
resetForm();
}
})(FormReq)

Resources