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 includes a setting, for each form, that lets you define a Submission Limit. This can be found in the Settings tab of your form. By placing a value in the field, you can define how many submissions your form is allowed to accept. Your form will no longer load when the number […]

HTML Forms can store all of your form submissions in your database. You can then view these Submissions from inside the WordPress admin.