Form validation is the process of checking user-entered data before it is submitted or processed. Validation helps ensure that required fields are filled correctly and that the application receives acceptable data.
In React Native, form validation is commonly performed using
useState, TextInput, event handlers and
conditional rendering.
Form validation checks whether the information entered by a user meets the rules required by the application.
For example:
The simplest validation is checking whether a required field is empty.
if (name.trim() === '') {
setError(
'Name is required'
);
return;
}
The trim() method removes unnecessary spaces from the
beginning and end of a string.
An error message can be stored in state.
const [error, setError] =
useState('');
When validation fails, update the error state.
setError(
'Name is required'
);
{error !== '' && (
<Text
style={{
color: 'red'
}}
>
{error}
</Text>
)}
The message is displayed only when the error state contains a value.
A simple email validation can check whether the value contains basic email-related characters.
if (!email.includes('@')) {
setError(
'Please enter a valid email'
);
return;
}
More complete validation rules can be used depending on application requirements.
const emailPattern =
/^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
setError(
'Enter a valid email address'
);
return;
}
A regular expression can be used when more structured email format validation is required.
A password can be checked for a minimum length.
if (password.length < 6) {
setError(
'Password must contain at least 6 characters'
);
return;
}
Registration forms often contain a password confirmation field.
if (password !== confirmPassword) {
setError(
'Passwords do not match'
);
return;
}
This checks whether both password values are identical.
A simple validation can check the length of the entered phone number.
if (phone.length !== 10) {
setError(
'Enter a valid phone number'
);
return;
}
The exact validation rule should match the application's intended phone number format.
You can check whether a value contains a valid number.
const amountNumber =
Number(amount);
if (
amount.trim() === '' ||
Number.isNaN(amountNumber)
) {
setError(
'Enter a valid amount'
);
return;
}
Numeric input can be checked against a minimum allowed value.
const ageNumber =
Number(age);
if (ageNumber < 18) {
setError(
'Age must be at least 18'
);
return;
}
const ageNumber =
Number(age);
if (ageNumber > 100) {
setError(
'Please enter a valid age'
);
return;
}
Minimum and maximum rules can be combined when necessary.
const handleSubmit = () => {
setError('');
if (name.trim() === '') {
setError(
'Name is required'
);
return;
}
if (email.trim() === '') {
setError(
'Email is required'
);
return;
}
if (password.length < 6) {
setError(
'Password is too short'
);
return;
}
};
One common approach is to validate all fields when the user presses the submit button.
<Button
title="Submit"
onPress={handleSubmit}
/>
The handleSubmit function performs validation before
continuing with the submission process.
Some applications provide validation feedback while the user is typing.
const handleEmailChange = (
text
) => {
setEmail(text);
if (
text !== '' &&
!text.includes('@')
) {
setEmailError(
'Enter a valid email'
);
} else {
setEmailError('');
}
};
Instead of using one error message for the entire form, each field can have its own error state.
const [nameError, setNameError] =
useState('');
const [emailError, setEmailError] =
useState('');
const [passwordError, setPasswordError] =
useState('');
This makes it possible to show the error next to the corresponding field.
<TextInput
value={email}
onChangeText={setEmail}
placeholder="Email"
/>
{nameError !== '' && (
<Text style={styles.error}>
{nameError}
</Text>
)}
Showing an error near the related field makes it easier for users to understand what needs to be corrected.
The input appearance can also change when an error exists.
<TextInput
style={[
styles.input,
emailError !== '' &&
styles.inputError
]}
value={email}
onChangeText={setEmail}
placeholder="Email"
/>
inputError: {
borderColor: 'red'
}
Errors should usually be cleared when the user corrects the input or when a new validation process starts.
setError('');
const handleSubmit = () => {
setError('');
// validation...
};
An input can be validated when the user leaves the field using
onBlur.
const validateEmail = () => {
if (
email !== '' &&
!email.includes('@')
) {
setEmailError(
'Invalid email'
);
} else {
setEmailError('');
}
};
<TextInput
value={email}
onChangeText={setEmail}
onBlur={validateEmail}
placeholder="Email"
/>
const [loading, setLoading] =
useState(false);
const handleSubmit = () => {
if (!validateForm()) {
return;
}
setLoading(true);
// Submit data
};
Validation should happen before starting the submission process.
const validateForm = () => {
if (name.trim() === '') {
setError(
'Name is required'
);
return false;
}
if (email.trim() === '') {
setError(
'Email is required'
);
return false;
}
setError('');
return true;
};
Returning true or false makes the validation
function reusable.
const [message, setMessage] =
useState('');
const handleSubmit = () => {
setError('');
setMessage('');
if (!validateForm()) {
return;
}
setMessage(
'Form submitted successfully!'
);
};
A success message can be displayed after the validation succeeds.
When form data will be sent to an API, validate the values before making the request.
const handleSubmit = async () => {
setError('');
if (!validateForm()) {
return;
}
// Send valid data
// to the API here.
};
Client-side validation helps provide quick feedback, but the backend should independently validate important data.
import React, {
useState
} from 'react';
import {
View,
Text,
TextInput,
Pressable,
ScrollView,
StyleSheet
} from 'react-native';
export default function App() {
const [name, setName] =
useState('');
const [email, setEmail] =
useState('');
const [password, setPassword] =
useState('');
const [confirmPassword,
setConfirmPassword] =
useState('');
const [error, setError] =
useState('');
const [message, setMessage] =
useState('');
const validateForm = () => {
if (name.trim() === '') {
setError(
'Name is required'
);
return false;
}
if (email.trim() === '') {
setError(
'Email is required'
);
return false;
}
const emailPattern =
/^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
setError(
'Enter a valid email address'
);
return false;
}
if (password.length < 6) {
setError(
'Password must contain at least 6 characters'
);
return false;
}
if (
password !== confirmPassword
) {
setError(
'Passwords do not match'
);
return false;
}
setError('');
return true;
};
const handleSubmit = () => {
setMessage('');
if (!validateForm()) {
return;
}
setMessage(
'Registration successful!'
);
};
return (
<ScrollView
contentContainerStyle={
styles.container
}
>
<Text style={styles.title}>
Registration Form
</Text>
<TextInput
style={styles.input}
value={name}
onChangeText={setName}
placeholder="Enter name"
autoCapitalize="words"
/>
<TextInput
style={styles.input}
value={email}
onChangeText={setEmail}
placeholder="Enter email"
keyboardType="email-address"
autoCapitalize="none"
/>
<TextInput
style={styles.input}
value={password}
onChangeText={setPassword}
placeholder="Enter password"
secureTextEntry
/>
<TextInput
style={styles.input}
value={confirmPassword}
onChangeText={setConfirmPassword}
placeholder="Confirm password"
secureTextEntry
/>
{error !== '' && (
<Text style={styles.error}>
{error}
</Text>
)}
{message !== '' && (
<Text style={styles.success}>
{message}
</Text>
)}
<Pressable
style={styles.button}
onPress={handleSubmit}
>
<Text
style={styles.buttonText}
>
Register
</Text>
</Pressable>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: {
padding: 20,
flexGrow: 1,
justifyContent: 'center'
},
title: {
fontSize: 28,
fontWeight: 'bold',
marginBottom: 20
},
input: {
borderWidth: 1,
borderColor: '#CBD5E1',
borderRadius: 8,
padding: 12,
marginBottom: 12
},
button: {
marginTop: 15,
padding: 14,
borderRadius: 8,
backgroundColor: '#2563EB',
alignItems: 'center'
},
buttonText: {
color: 'white',
fontWeight: 'bold'
},
error: {
color: 'red',
marginTop: 5
},
success: {
color: 'green',
marginTop: 5
}
});
| Field | Example Validation |
|---|---|
| Name | Required and not empty |
| Required and valid email format | |
| Password | Minimum required length |
| Confirm Password | Must match password |
| Phone | Required length or format |
| Age | Valid numeric range |
| Message | Required when the field is mandatory |
Create Form Fields
↓
Create State Variables
↓
Create Error States
↓
Connect Inputs with State
↓
Create Validation Function
↓
Check Required Fields
↓
Validate Formats and Values
↓
Display Error Messages
↓
Stop if Validation Fails
↓
Submit Valid Data
↓
Show Success Message
↓
Reset Form When Required
Form validation is an important part of building reliable React Native applications. Good validation gives users clear feedback, prevents incomplete submissions and helps ensure that the application processes appropriate data.
Question: What is the main purpose of form validation?