Forms And Validations In React Native
Forms:
Forms are essential part of any application, form
inputs are key components for an user to interact with the application
specifically in sign in, signup, content creation , commenting etc..
To ensure seamless user experience, a form component consists of more input fields that allow users to enter their credentials. This can vary from handling form state, input field validation, handling errors, form submission, and so on.
Formik:
This is a open source library in react And react
native, that helps the user to create and handle the forms in a easy and
efficient way .it is a library that assists you with the 3 most disturbing
parts of form building in react-native. It also helps in keeping things organized
by building, testing, and refactoring your forms.
Handling form submission
Validation and error messages
Managing form values of form state.
Getting
started with Formik:
First setup the environment and create a react
native project.
Installing
The Formik Library:
You can install the Formik library using the below
Command,
npm
i formik
Creating
A Simple Sign Up Form:
Example:
import React from 'react'
import { View,Text,StyleSheet,TextInput,Button} from 'react-native'
import { Formik } from 'formik'
const App=()=>{
return(
<View style={styles.scr}>
<Text>login form</Text>
<Formik
initialValues={{ email: '',
name:'' }}
onSubmit={values => console.log(values)}
>
{({ handleChange,handleSubmit,values }) => (
<View style={{flex:1}}>
<TextInput
style={styles.ip}
placeholder='Enter Email'
onChangeText={handleChange('email')}
value={values.email}
/>
<TextInput
style={styles.ip}
placeholder='enter Your Name'
onChangeText={handleChange('name')}
value={values.name}
/>
<Button onPress={handleSubmit} title="Submit" />
</View>
)}
</Formik>
</View>
)
}
export default App
const styles = StyleSheet.create({
ip:{borderWidth:1,backgroundColor:'lightgrey',
borderColor:'black',fontWeight:'bold',fontSize:15,
width:'90%',margin:10},
scr:{flex:1,
backgroundColor:'skyblue',
justifyContent:'center'}
})
First you will import react and the native
components needed for creating the form then you will import formik.
Initial
values:
Initial field values of the form, Formik will make
these values available to render methods component as values.Even if your form
is empty by default, you must initialize all fields with initial values
otherwise React native will throw an
error.
handleChange:
it is a general input event handler .it will take
care of updating the values .it reducing the code for updating the state.
handleSubmit:
it is similar to to on press function while the
button pressed it will execute the function onsubmit.
OnSubmit:
This will define what action to perform while the button pressed. here we
logged our values into the console so we get output in the console.
Output:
Let us create a list and update the values into the
list.
Example:
import React, { useState } from 'react'
import { View,Text,StyleSheet,TextInput,Button, FlatList} from 'react-native'
import { Formik } from 'formik'
const App=()=>{
const [list ,setList]=useState([{email:'mani.com',name:'mani'},
{email:'aji.com',name:'aji'}])
return(
<View style={styles.scr}>
<Text style={{padding:10,fontWeight:'bold',fontSize:20,color:'darkblue'}}>registeration form</Text>
<View style={{flex:1}}>
<Formik
initialValues={{ email: '',
name:'' }}
onSubmit={(values)=>{setList ((prevlist)=>{return[...prevlist,values
]})
}}
>
{({ handleChange,handleSubmit,values }) => (
<View style={{flex:1}}>
<TextInput
style={styles.ip}
placeholder='Enter Email'
onChangeText={handleChange('email')}
value={values.email}
/>
<TextInput
style={styles.ip}
placeholder='enter Your Name'
onChangeText={handleChange('name')}
value={values.name}
/>
<Button onPress={handleSubmit} title="Submit" />
</View>
)}
</Formik>
</View>
<View style={{flex:1,height:100}}>
<Text style={{padding:10,fontWeight:'bold',color:'darkblue',fontSize:20}}> Users</Text>
<FlatList
data={list}
renderItem={({item})=>(
<View style={{backgroundColor:'white',margin:10}}>
<Text style={{padding:10,fontWeight:'bold'}}>Email: {item.email}</Text>
<Text style={{padding:10,fontWeight:'bold'}}> Name: {item.name}</Text>
</View>
)}
/>
</View>
</View>
)
}
export default App
const styles = StyleSheet.create({
ip:{borderWidth:1,backgroundColor:'lightgrey',
borderColor:'black',fontWeight:'bold',fontSize:15,
width:'90%',margin:10},
scr:{flex:1,
backgroundColor:'skyblue',
justifyContent:'center'}
})
By pressing the button after giving the input
onsubmit function from formik will update the list values.
Output:
Now We Add validations for the form
Validations:
Form validation is a “technical process where a form
checks if the information provided by a user is correct.” The form will either
alert the user that they messed up and need to fix something to proceed.
Yup:
Yup is a JavaScript schema builder for value parsing
and validation. The schema allows input controls to validate quickly. We can
quickly validate email input control even you can set the custom messages with
it. Validating and managing various input Field types is also easy with Yup.
Installation:
You can install the library by using the following
command,
Npm I yup
Creating
the validation schema:
After installing import yup and create a function schema
for the object. outside the component.
const Schema=yup.object({
email:yup.string().required().min(8).max(20).email(),
name:yup.string().min(5).max(15).required()
})
Then pass the schema as a function for validation
schema inside the Formik.
<Formik
validationSchema={ Schema}
initialValues={{ email: '',
name:'' }}
onSubmit={(values)=>{setList ((prevlist)=>{return[...prevlist,values
]})
}}
>
if the inputs from the user does not matches the
schema we created then the formic will not allow the on submit action . the on
submit action only performed when the inputs from the user meets the schema
condition.
errors:
The Formik library comes with the property called
errors, this property will give a alert message about that the user facing and
help to overcome the errors in the user input.
First you need to add the errors insidethe
props.then pass the errors function after every input like,
<Formik
validationSchema={ Schema}
initialValues={{ email: '',
name:'' }}
onSubmit={(values)=>{setList ((prevlist)=>{return[...prevlist,values
]})
}}
>
{({ handleChange,handleSubmit,values ,errors}) => (
<View style={{flex:1}}>
<TextInput
style={styles.ip}
placeholder='Enter Email'
onChangeText={handleChange('email')}
value={values.email}
/>
<Text>{errors.email}</Text>
<TextInput
style={styles.ip}
placeholder='enter Your Name'
onChangeText={handleChange('name')}
value={values.name}
/>
<Text>{errors.name}</Text>
<Button onPress={handleSubmit} title="Submit" />
</View>
)}
</Formik>
this will display the errors when the submit button
is pressed.
Output:
Handleblur:
The handleblur property of the formic will show the
error while the user coming out of the input field rather than showing error
after pressing the submit button.
Touched:
The touched property is used for displaying the
error only after the input is given /or input field is touched rather then
displaying error before giving an input:
Example:
<Formik
validationSchema={ Schema}
initialValues={{ email: '', name:'' }}
onSubmit={(values)=>{setList ((prevlist)=>{return[...prevlist,values]})
}}
>
{({ handleChange,handleSubmit,values ,errors,handleBlur,touched}) => (
<View style={{flex:1}}>
<TextInput
style={styles.ip}
placeholder='Enter Email'
onChangeText={handleChange('email')}
value={values.email}
onBlur={handleBlur('email')}
/>
<Text style={{color:'red',fontWeight:'bold'}}>{touched.email && errors.email}</Text>
<TextInput
style={styles.ip}
placeholder='enter Your Name'
onChangeText={handleChange('name')}
value={values.name}
onBlur={handleBlur('name')}
/>
<Text style={{color:'red',fontWeight:'bold'}}>{touched.name && errors.name}</Text>
<Button onPress={handleSubmit} title="Submit" />
</View>
)}
</Formik>
Output:
Comments
Post a Comment