Skip to content

Enforcing validation on user input

Greg Bowler edited this page Feb 28, 2023 · 16 revisions

Adding attributes like required to HTML inputs automatically enables client-side validation in the browser, but to enforce validation on the server, this library has to be triggered in your PHP code.

With an HTMLDocument representing the current page (where the form is), and a reference to the <form> element you wish to validate, call the validate() function of a Validator object, passing in the reference to the Form and the submitted user input to check against.

The validate() function will throw a ValidationException if there are any errors with the form's validation. You can catch this exception and output appropriate error messages on the invalid fields.

WebEngine example

In PHP.Gt/WebEngine applications, the HTMLDocument, Validator and Input are all available via dependency injection, using the do function's parameters.

use Gt\Dom\HTMLDocument;
use Gt\DomValidation\Validator;
use Gt\Input\Input;
use Gt\DomValidation\ValidationException;

function do_submit(HTMLDocument $document, Validator $validator, Input $input):void {
// First, obtain a reference to the form we wish to validate.
	$form = $document->querySelector("#example-form");

	try {
// Then "try" to validate the form with the submitted user input:
		$validator->validate($form, $input);
	}
	catch(ValidationException) {
// If there are any validation errors, we can iterate over them to display
// to the page, and return early as to not action the user input.
		foreach($validator->getLastErrorList() as $name => $message) {
// Here we can add an attribute to the parent of the input, for displaying
// the error message using CSS, for example.
			$errorElement = $form->querySelector("[name=$name]");
			$errorElement->parentNode->dataset->validationError = $message;
		}
        
// Return early so user input isn't used when there are validation errors. 
		return;
	}

// Finally, if the input contains no validation errors, continue as usual.
}
Clone this wiki locally