PHP code example of phpgt / domvalidation

1. Go to this page and download the library: Download phpgt/domvalidation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phpgt / domvalidation example snippets


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

// Assume this function is triggered when POST data arrives.
function handleSubmit($inputData) {
	$document = new HTMLDocument(file_get_contents("example-form.html"));
// First, obtain a reference to the form we wish to validate.
	$form = $document->querySelector("#example-form");
	$validator = new Validator();

	try {
// Within a try/catch, pass the form and the user input into the Validator.
		$validator->validate($form, $inputData);
	}
	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.
	sendInputToDatabase($inputData);
}