Mahamudul Hasan Rubel
HomeBlogCoursesAboutProjectsSkillsExperiencePhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • Blog
  • Courses
  • About
  • Projects
  • Skills
  • Experience
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 26 of the Intermediate WordPress Plugins: REST API & React Admin course
WordPressJune 26, 20263 min read

Input Validation and Error Handling for WordPress REST API & React

Learn to build robust input validation for your WordPress plugin. Discover how to provide instant client-side feedback and handle server-side errors gracefully.

WordPressREST APIReactValidationUXError Handlingphpplugin-development

Previously in this course, we covered implementing nonce verification for WordPress REST API security. While securing the transport layer is critical, a truly professional plugin must also handle the "happy path" failures that occur when users provide invalid data.

In this lesson, we are moving beyond basic data processing to build a resilient feedback loop. We will implement validation at the UI level to improve UX and enforce strict validation on the server to prevent bad data from reaching the database, ensuring that our error handling strategy is both transparent and helpful to the end user.

Why Dual-Layer Validation Matters

Validation isn't just about security; it’s about communication. If a user submits a form with a missing title, waiting for a round-trip to the server to find out is a waste of resources and time.

  1. Client-Side Validation: Provides instant feedback. It prevents unnecessary network requests and keeps the UI responsive.
  2. Server-Side Validation: Acts as the "source of truth." Never trust the client; always re-verify data in your PHP REST callback before persisting it to the database.

Implementing Structured JSON Error Responses

In WordPress, the REST API expects specific response formats. When validation fails on the server, you should return a WP_Error object, which the API automatically converts into a JSON error response.

Here is how to structure your PHP callback to return meaningful errors:

PHP
#6A9955">// In your REST API callback
public function create_knowledge_base_item( WP_REST_Request $request ) {
    $title = sanitize_text_field( $request->get_param( 'title' ) );

    if ( empty( $title ) ) {
        return new WP_Error( 
            'invalid_title', 
            __( 'The knowledge base title is required.', 'my-plugin' ), 
            array( 'status' => 400 ) 
        );
    }

    #6A9955">// Process data...
}

The 400 status code tells the client that the request was malformed, allowing your JavaScript to catch the error and display it appropriately.

Building Client-Side Validation Logic

In your React admin dashboard, you should validate input before triggering the API call. Using the useState hook, we can manage both the data and the error state.

JAVASCRIPT
import { useState } from CE9178">'@wordpress/element';
import apiFetch from CE9178">'@wordpress/api-fetch';

const KnowledgeBaseForm = () => {
    const [title, setTitle] = useState(CE9178">'');
    const [error, setError] = useState(null);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError(null); // Reset error

        // Client-side validation
        if (title.length < 5) {
            setError(CE9178">'Title must be at least 5 characters long.');
            return;
        }

        try {
            await apiFetch({
                path: CE9178">'/my-plugin/v1/items',
                method: CE9178">'POST',
                data: { title },
            });
        } catch (err) {
            // Handle server-side errors
            setError(err.message || CE9178">'An unexpected error occurred.');
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            {error && <div className="notice notice-error">{error}</div>}
            <input value={title} onChange={(e) => setTitle(e.target.value)} />
            <button type="submit">Save</button>
        </form>
    );
};

Hands-on Exercise

  1. Update your REST callback: Modify your POST endpoint to check for a minimum length of 5 characters for the title, returning a WP_Error if it fails.
  2. Enhance your React Form: Add a validation function that runs inside handleSubmit. Ensure the error message state is cleared when the user starts typing again.
  3. Test the loop: Intentionally send a short title and verify that your UI displays the error returned by the server.

Common Pitfalls

  • Trusting the Client: Never assume that because you have client-side validation, the data is safe. Always sanitize and validate in PHP.
  • Generic Error Messages: Avoid "An error occurred." Be specific. Tell the user exactly what failed (e.g., "Title is required") so they can fix it.
  • Swallowing Errors: When using try/catch in JS, ensure you actually log or display the error. Silently failing is the fastest way to lose a user's trust. For more on professional patterns, see Managing Errors: Professional Error Handling in React.

Recap

By implementing validation on both sides, we create a robust experience. The client-side logic provides the "snappy" feel users expect, while the server-side validation maintains data integrity. When things go wrong, structured JSON responses ensure our UI can communicate clearly with the user, turning potential frustrations into actionable feedback.

Up next: We will discuss how to further secure your plugin by protecting admin screens based on user roles and permissions.

Previous lessonAdvanced Sanitization TechniquesNext lesson Protecting Admin Screens
Back to Blog

Similar Posts

WordPressJune 26, 20264 min read

Debugging React in the WordPress Admin: A Practical Guide

Debugging React in the WordPress admin requires a systematic approach. Learn to inspect component hierarchies, trace data store actions, and analyze API traffic.

Read more
WordPressJune 25, 20263 min read

Implementing Resolvers for Data Fetching in WordPress @wordpress/data

Learn how to implement resolvers in @wordpress/data to automate API data fetching. Discover how to sync your React state with the WordPress REST API seamlessly.

Part of the course

Intermediate WordPress Plugins: REST API & React Admin

intermediate · Lesson 26 of 45

  1. 1

    Setting up the WordPress Development Environment

    3 min
  2. 2

    Introduction to @wordpress/scripts

    3 min
  3. 3

    Configuring ESLint and Prettier

    3 min
Read more
WordPressJune 25, 20263 min read

Implementing CRUD in the Admin UI: WordPress REST API & React

Master CRUD operations in your WordPress admin dashboard. Learn to trigger API requests from React forms and lists to build truly interactive plugins.

Read more
4

Localizing Data for JavaScript

3 min
  • 5

    Anatomy of a REST API Endpoint

    3 min
  • 6

    Implementing REST API Permission Callbacks

    3 min
  • 7

    Handling GET Requests in REST API

    3 min
  • 8

    Validating and Sanitizing API Arguments

    4 min
  • 9

    Creating POST Endpoints for Data Submission

    3 min
  • 10

    Updating Existing API Resources

    3 min
  • 11

    Handling Asynchronous State in React

    3 min
  • 12

    Building the Knowledge Base Service Layer

    3 min
  • 13

    Scaffolding the React Admin Dashboard

    3 min
  • 14

    Working with @wordpress/components

    3 min
  • 15

    Creating a React Form for Submissions

    3 min
  • 16

    Implementing CRUD in the Admin UI

    3 min
  • 17

    Understanding WordPress Data Store Architecture

    4 min
  • 18

    Registering a Custom Data Store

    3 min
  • 19

    Writing Selectors for Data Access

    3 min
  • 20

    Defining Actions and Reducers

    3 min
  • 21

    Implementing Resolvers for Data Fetching

    3 min
  • 22

    Optimizing Performance with Selectors

    3 min
  • 23

    Handling Complex State Dependencies

    4 min
  • 24

    Implementing Nonce Verification

    4 min
  • 25

    Advanced Sanitization Techniques

    3 min
  • 26

    Input Validation and Error Handling

    3 min
  • 27

    Protecting Admin Screens

    3 min
  • 28

    Production Build Pipeline

    3 min
  • 29

    Debugging React in the WordPress Admin

    4 min
  • 30

    Building Search and Filter Functionality

    3 min
  • 31

    Internationalization in React

    Coming soon
  • 32

    Managing File Uploads via REST API

    Coming soon
  • 33

    Optimizing API Response Times

    Coming soon
  • 34

    Working with Date and Time in React

    Coming soon
  • 35

    Implementing Drag-and-Drop Sorting

    Coming soon
  • 36

    Creating Custom Hooks for API Logic

    Coming soon
  • 37

    Integrating with Gutenberg Blocks

    Coming soon
  • 38

    Handling Conflict Resolution

    Coming soon
  • 39

    Building a Modal Confirmation System

    Coming soon
  • 40

    Implementing Activity Logging

    Coming soon
  • 41

    Using Webpack Aliases

    Coming soon
  • 42

    Unit Testing API Endpoints

    Coming soon
  • 43

    Unit Testing React Components

    Coming soon
  • 44

    Handling Large Datasets with GraphQL

    Coming soon
  • 45

    Implementing Real-time Updates with Web

    Coming soon
  • View full course