Custom form validation

HTML Forms will perform the following form validation by itself:

  • All input fields marked as required.
  • All fields of type “email”.

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_HAM” contains the value “iberico ham”.

add_filter( 'hf_validate_form', function( $error_code, $form, $data ) {
	if( $data['BEST_HAM'] !== 'iberico_ham' ) {
		$error_code = 'invalid_ham_choice'; 

	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_invalid_ham_choice', function( $message ) {
    return 'Sorry, but iberico ham is really the best ham.';