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.

Similar Posts