Custom form validation

Alex Holsgrove asked
forms error-handling
via

I have created a basic form which can be POST to admin-post.php and also submitted via an AJAX call to admin-ajax.php. Both submissions work correctly, use the nonce for a little extra security, and I can process the data as required.

My question and problem is how, with the regular form POST to admin-post.php, to send back a message to the form with either a success message string, or an error - which could be a string, or an array of invalid form field entries? With the AJAX call I can simply echo a json encoded response.

I know there is no session set unless I manually call session_start() and also using globals isn’t ideal. Is there some other sort of storage or system I can use to pass these messages?

I’ve used transients before - would these be suitable? I understand the transient data may not be available at any given moment so perhaps not?

Could I use the WP_Error class?


Answer
via

Yes, you’d use a JSON response containing an error property.

<?php
echo json_encode( [
    'error' => [
        'code'    => 'my_error_code',
        'message' => 'My error message.',
        'data'    => [any additional data you need],
    ],
] );

Your AJAX callback should look for the error and adapt accordingly.


For the regular POST, you’d want to generate HTML markup that produces a WP Notice, or that produces markup that you will style as a notice. See: Complete Guide to Notices

Share This
Posted in: