Custom Form Validation

Custom form validation provides a way to validate a live checkout before it is paid. By default, SureCart handles some existing validation, such as validating product availability. However, in some cases, you may want to add your own custom form validation.

SureCart provides a convenient WordPress filter that allows you to run any custom validations before the checkout is finalized and ready for payment. If any errors are added during this step, the order will not be finalized and will not be available for payment.

The surecart/checkout/validate filter hook is used to validate the checkout before finalization.

apply_filters(
  'surecart/checkout/validate',
  $errors,
  $args,
  $request
)

Using this filter will allow you to inspect the request, existing errors, and any other relevant arguments to perform your custom form validation.

Example 1: How to block an IP address from completing a checkout

SureCart actively monitors malicious actors on a regular basis. However, you may want to disallow specific IP addresses to prevent purchases. This can be achieved by inspecting an IP address and adding a custom error message. Errors can be added using the following code:

$errors->add( 'error_code', 'Error message' );

The error message will be displayed on the front-end of the site. The code can be used to identify the error, even if it has been translated into a different language. In this example, you can block an IP address to disallow purchases.

add_filter(
	'surecart/checkout/validate',
	function( $errors ) {
		// get the IP address with php.
		$ip_address = $_SERVER['HTTP_CLIENT_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '';

		// if the ip address is in the array, add an error.
		if ( in_array( $ip_address, [ '62.120.200.127' ] ) ) {
			$errors->add( 'blocked', 'You are not allowed to purchase.' );
		}

		return $errors;
	}
);

What’s Next