React Formik and simple form validation.

Let’s start with creating react application in our local environment. For that we open the command line and go to a desktop folder using:

cd Desktop/

After that create react application with:

npx create-react-app testapp

After the React project is created on your computer, open it with the code editor you used and open the App.js file. Clear App.js file and copy it for starting.

export default function App() {
 return (
    <div className="App">
       <form>
       <label htmlFor='name'>Name</label>
<input id='name' type='text' placeholder='Name' />
       <label htmlFor='email'>Email</label>
<input id='email' type='email' placeholder='Email'/>
       <button type='submit'>Submit</button>
      </form>
  </div>
);
}

This is the basic form for our application.

Let’s add the formik package to our application. Open up the terminal write:

npm i formik

Now we going to use useFormik() custom react hook. Internally, Formik uses useFormik to create the <Formik> component (which renders a React Context Provider).

Import useFormik to our project with:

import { useFormik } from ‘formik’

And let’s call it in our component

const formik = useFormik({})

In the form which we create, we have 2 fields: name and email. For the managing form state, we first declare initial values of input fields like that. Initial values declared in the useFormik hook.

const formik = useFormik({
initialValues:{
name:'',
email:''
}
})

if we console log for the values of formik elements write this line

console.log(formik.values);

And you will see

Formik detects the input element changes with the onChange function and alse we declare the value of the input using formik. For that add onChange function and value to <input/> an element like below.

*Name input*
<input 
id=’name’
type=’text’
placeholder=’Name’
onChange={formik.handleChange}
value={formik.values.name }
/>
*Email input*
<input 
id='email'
type='email'
placeholder='Email'
onChange={formik.handleChange}
value={formik.values.email } />

Lets console log again and type something into the input field

You see I write my name to the input and handleChange detect that.

We write onChange function and detect changes in input fields.

Let us look at how we handle the form on submit:

? First, add the onSubmit function to tohe <form/> item like that:

<form onSubmit={formik.handleSubmit}>

formik.handleChange comes from library.

?Second, add onSubmit to the useFormik hook. This onSubmit is the object and it takes the arrow function. And inside this arrow function console log the input values.

const formik = useFormik({
initialValues:{
name:’’,
email:’’
},
onSubmit:values=>{
console.log(‘Form data’,values);
}})

Let’s test it, write anything into inputs and click submit button.

If you click submit button you will see it will work.

? And Let’s write Validation to our form

For validation we again use useFormik. Let’s see how

const formik = useFormik({
initialValues:{
name:’’,
email:’’
},
onSubmit:values=>{
console.log(‘Form data’,values);
},
validate:values=>{
let errors = {};
 if(!values.name){
errors.name = 'Required!'
}
if(!values.email){
errors.email= 'Required!'
}else if(!/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i.test(values.email)){
errors.email = 'Invalid email format!'
}
 return errors;
}
})

inside validation object, we use if statements and query is the name or email section empty or not if the input field is empty “Required !” error added to errors object. For an email query, we also use regex for the correct format of email.

Regex for email : !/^(([^<>()\[\]\\.,;:\s@”]+(\.[^<>()\[\]\\.,;:\s@”]+)*)|(“.+”))@((\[[0–9]{1,3}\.[0–9]{1,3}\.[0–9]{1,3}\.[0–9]{1,3}])|(([a-zA-Z\-0–9]+\.)+[a-zA-Z]{2,}))$/i.test(values.email)

If we log errors like that: console.log(‘Errors’ , formik.errors); we see errors.

If the email section not empty but wrong format

?️ Let’s display errors on the screen

Inside the <label> tag we use curly brackets and use the ternary expression for interrogating errors have or not. If an error has shown on the screen.

*For name *
<label htmlFor='name'>Name &nbsp;
{formik.errors.name && <div className="error">{formik.errors.name} </div>}
</label>
*For email*
<label htmlFor='email'>Email&nbsp;
{formik.errors.email&& <div className="error">{formik.errors.email}
</div>}
</label>

You will see an error on the screen

Codes of Simple form Validation: Github repo

For Supporting me: Patreon


React Formik and simple form validation. was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Simuratli

Let's start with creating react application in our local environment. For that we open the command line and go to a desktop folder using:

cd Desktop/

After that create react application with:

npx create-react-app testapp

After the React project is created on your computer, open it with the code editor you used and open the App.js file. Clear App.js file and copy it for starting.

export default function App() {
 return (
    <div className="App">
       <form>
       <label htmlFor='name'>Name</label>
<input id='name' type='text' placeholder='Name' />
       <label htmlFor='email'>Email</label>
<input id='email' type='email' placeholder='Email'/>
       <button type='submit'>Submit</button>
      </form>
  </div>
);
}

This is the basic form for our application.

Let's add the formik package to our application. Open up the terminal write:

npm i formik

Now we going to use useFormik() custom react hook. Internally, Formik uses useFormik to create the <Formik> component (which renders a React Context Provider).

Import useFormik to our project with:

import { useFormik } from ‘formik’

And let's call it in our component

const formik = useFormik({})

In the form which we create, we have 2 fields: name and email. For the managing form state, we first declare initial values of input fields like that. Initial values declared in the useFormik hook.

const formik = useFormik({
initialValues:{
name:'',
email:''
}
})

if we console log for the values of formik elements write this line

console.log(formik.values);

And you will see

Formik detects the input element changes with the onChange function and alse we declare the value of the input using formik. For that add onChange function and value to <input/> an element like below.

*Name input*
<input 
id=’name’
type=’text’
placeholder=’Name’
onChange={formik.handleChange}
value={formik.values.name }
/>
*Email input*
<input 
id='email'
type='email'
placeholder='Email'
onChange={formik.handleChange}
value={formik.values.email } />

Lets console log again and type something into the input field

You see I write my name to the input and handleChange detect that.

We write onChange function and detect changes in input fields.

Let us look at how we handle the form on submit:

? First, add the onSubmit function to tohe <form/> item like that:

<form onSubmit={formik.handleSubmit}>
formik.handleChange comes from library.

?Second, add onSubmit to the useFormik hook. This onSubmit is the object and it takes the arrow function. And inside this arrow function console log the input values.

const formik = useFormik({
initialValues:{
name:’’,
email:’’
},
onSubmit:values=>{
console.log(‘Form data’,values);
}})

Let's test it, write anything into inputs and click submit button.

If you click submit button you will see it will work.

? And Let's write Validation to our form

For validation we again use useFormik. Let's see how

const formik = useFormik({
initialValues:{
name:’’,
email:’’
},
onSubmit:values=>{
console.log(‘Form data’,values);
},
validate:values=>{
let errors = {};
 if(!values.name){
errors.name = 'Required!'
}
if(!values.email){
errors.email= 'Required!'
}else if(!/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i.test(values.email)){
errors.email = 'Invalid email format!'
}
 return errors;
}
})

inside validation object, we use if statements and query is the name or email section empty or not if the input field is empty “Required !” error added to errors object. For an email query, we also use regex for the correct format of email.

Regex for email : !/^(([^<>()\[\]\\.,;:\s@”]+(\.[^<>()\[\]\\.,;:\s@”]+)*)|(“.+”))@((\[[0–9]{1,3}\.[0–9]{1,3}\.[0–9]{1,3}\.[0–9]{1,3}])|(([a-zA-Z\-0–9]+\.)+[a-zA-Z]{2,}))$/i.test(values.email)

If we log errors like that: console.log(‘Errors’ , formik.errors); we see errors.

If the email section not empty but wrong format

?️ Let's display errors on the screen

Inside the <label> tag we use curly brackets and use the ternary expression for interrogating errors have or not. If an error has shown on the screen.

*For name *
<label htmlFor='name'>Name &nbsp;
{formik.errors.name && <div className="error">{formik.errors.name} </div>}
</label>
*For email*
<label htmlFor='email'>Email&nbsp;
{formik.errors.email&& <div className="error">{formik.errors.email}
</div>}
</label>

You will see an error on the screen

Codes of Simple form Validation: Github repo

For Supporting me: Patreon


React Formik and simple form validation. was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Simuratli


Print Share Comment Cite Upload Translate Updates
APA

Simuratli | Sciencx (2021-04-14T18:04:25+00:00) React Formik and simple form validation.. Retrieved from https://www.scien.cx/2021/04/14/react-formik-and-simple-form-validation/

MLA
" » React Formik and simple form validation.." Simuratli | Sciencx - Wednesday April 14, 2021, https://www.scien.cx/2021/04/14/react-formik-and-simple-form-validation/
HARVARD
Simuratli | Sciencx Wednesday April 14, 2021 » React Formik and simple form validation.., viewed ,<https://www.scien.cx/2021/04/14/react-formik-and-simple-form-validation/>
VANCOUVER
Simuratli | Sciencx - » React Formik and simple form validation.. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/14/react-formik-and-simple-form-validation/
CHICAGO
" » React Formik and simple form validation.." Simuratli | Sciencx - Accessed . https://www.scien.cx/2021/04/14/react-formik-and-simple-form-validation/
IEEE
" » React Formik and simple form validation.." Simuratli | Sciencx [Online]. Available: https://www.scien.cx/2021/04/14/react-formik-and-simple-form-validation/. [Accessed: ]
rf:citation
» React Formik and simple form validation. | Simuratli | Sciencx | https://www.scien.cx/2021/04/14/react-formik-and-simple-form-validation/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.