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 offers support for Google reCAPTCHA v3. The process is simple. Step #1 Generate a Site Key and a Secret Key for your site by registering at https://www.google.com/recaptcha/admin/. Step #2 With your keys in hand, add them to the Google reCAPTCHA v3 fields in the HTML Forms plugin settings screen: Step #3 Confirm your […]

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 […]