Lesson 37 of 60 – Form Validation in React Native
62%

Form Validation in React Native

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.

Note: Client-side validation improves the user experience, but important data should also be validated on the server when it is sent to a backend.

1. What is Form Validation?

Form validation checks whether the information entered by a user meets the rules required by the application.

For example:

  • Name should not be empty.
  • Email should have an acceptable format.
  • Password may require a minimum length.
  • Phone number may require a specific number of digits.
  • Required fields should contain values.

2. Why is Form Validation Important?

  • Prevents incomplete form submissions.
  • Helps users correct mistakes.
  • Improves the user experience.
  • Keeps application data more consistent.
  • Prevents unnecessary requests.
  • Provides immediate feedback.

3. Required Field Validation

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.

4. Creating Error State

An error message can be stored in state.

const [error, setError] =
    useState('');

When validation fails, update the error state.

setError(
    'Name is required'
);

5. Displaying an Error Message

{error !== '' && (

    <Text
        style={{
            color: 'red'
        }}
    >
        {error}
    </Text>

)}

The message is displayed only when the error state contains a value.

6. Validating Email

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.

7. Email Validation with a Regular Expression

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.

8. Password Length Validation

A password can be checked for a minimum length.

if (password.length < 6) {

    setError(
        'Password must contain at least 6 characters'
    );

    return;

}

9. Confirm Password Validation

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.

10. Phone Number Validation

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.

11. Numeric Validation

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;

}

12. Minimum Value Validation

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;

}

13. Maximum Value Validation

const ageNumber =
    Number(age);

if (ageNumber > 100) {

    setError(
        'Please enter a valid age'
    );

    return;

}

Minimum and maximum rules can be combined when necessary.

14. Multiple Field Validation

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;

    }

};

15. Validating on Submit

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.

16. Validating While Typing

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('');

    }

};

17. Field-Specific Error State

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.

18. Showing Error Below an Input

<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.

19. Input Border for Validation

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'
}

20. Clearing Errors

Errors should usually be cleared when the user corrects the input or when a new validation process starts.

setError('');

const handleSubmit = () => {

    setError('');

    // validation...

};

21. Validation with onBlur

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"
/>

22. Form Validation with Loading State

const [loading, setLoading] =
    useState(false);

const handleSubmit = () => {

    if (!validateForm()) {

        return;

    }

    setLoading(true);

    // Submit data

};

Validation should happen before starting the submission process.

23. Creating a validateForm Function

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.

24. Validation and Success Message

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.

25. Validation Before API Submission

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.

26. Common Validation Mistakes

  • Validating only one field.
  • Not checking required fields.
  • Displaying unclear error messages.
  • Not clearing old errors.
  • Allowing submission before validation.
  • Using incorrect validation rules.
  • Not handling empty strings.
  • Ignoring loading state during submission.
  • Relying only on client-side validation for important data.
  • Making validation logic difficult to maintain.

27. Complete Form Validation Example

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
    }

});

28. Form Validation Best Practices

  • Validate required fields.
  • Use clear and helpful error messages.
  • Validate values before submission.
  • Use suitable validation rules for each field.
  • Show errors close to the relevant field when possible.
  • Clear errors when the input becomes valid.
  • Keep validation logic organized.
  • Prevent repeated submissions when necessary.
  • Use server-side validation for important submitted data.
  • Do not rely only on client-side validation for security.

29. Common Validation Rules

Field Example Validation
Name Required and not empty
Email 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

30. Complete Form Validation Workflow

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.

📌 Key Points

  • Form validation checks user-entered information.
  • Required fields should be checked before submission.
  • Email, password, phone and numeric values can have specific validation rules.
  • Error messages should clearly explain what needs to be corrected.
  • Validation can happen on submit, while typing or when an input loses focus.
  • Separate error states can be created for individual fields.
  • Validation should happen before API submission.
  • Loading state can help prevent repeated submissions.
  • Client-side validation improves user experience.
  • Important data should also be validated on the server.

🧠 Quick Quiz

Question: What is the main purpose of form validation?