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 has the value “carrot”.

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!';
});