Custom Form Validation

HTML Forms will perform the following form validation by itself:

  • All input fields marked as required should have a non-empty value.
  • All fields of type “email” should have a value that looks like an email address, or no value at all (if not required).

If you want to perform additional form validation, then you can do so by hooking into the hf_validate_form filter hook.

The following example will only accept the form submission if the field named “BEST_VEGETABLE” is filled and the value “carrot” is submitted.

add_filter( 'hf_validate_form', function( $error_code, $form, $data ) {
	if( ! isset($data['BEST_VEGETABLE']) || $data['BEST_VEGETABLE'] !== 'carrot' ) {
		$error_code = 'wrong_answer'; 
	}

	return $error_code;
}, 10, 3 );

Showing a Custom Error Message

The $error_code indicates what message should be shown to the person filling out the form. Since we did not register a message with that error code, the plugin will default to showing the general error message instead.

Let’s improve upon this by showing a more detailed error message describing exactly why the form validation failed.

add_filter( 'hf_form_message_wrong_answer', function( $message ) {
    return 'Sorry, but the best vegetable is a carrot!';
});

Related Posts from Our Knowledge Base

HTML Forms Premium adds an action to let you connect your form data to an external service using a webhook. This feature helps unlock the base plugin in an incredible number of ways. You can send data from your visitors to third-party applications or your own internal software tools. How to Create a Webhook Action […]

Creating your first form with the HTML Forms WordPress plugin is quick and simple. You’ll be up and running in seconds.