Skip to content

Displaying error messages

Greg Bowler edited this page Mar 5, 2023 · 2 revisions

Here's an example function that applies the default validation rules, leaving the exception handling empty for now.

The Input object represents any iterable<string, string> of user input, which is the type of data the Validator expects.

We also need an instance of the HTMLDocument, so we can obtain a reference to the current <form>, and to interact with the page to add the error messages.

function example(Input $input, Validator $validator, HTMLDocument $document):void {
	$form = $document->forms[0];

	try {
		$validator->validate($form, $input);
	}
	catch(ValidationException $exception) {
// ... we'll talk about the exception in detail below ...
	}
}

The ValidationException will be thrown if any of the fields within the provided <form> have invalid data represented in the provided user input, and within the catch block, we can display appropriate messages next to the corresponding fields using the following code example:

foreach($validator->getLastErrorList() as $fieldName => $errorMessage) {
// The $fieldName string corresponds to the `name` attribute of the input element,
// and the $errorMessage string contains the hint message corresponding to the type of error.

// We can get a reference of the invalid form element by searching by its name attribute:
	$element = $form->querySelector("[name='$fieldName']");

// Then we can output the error message somewhere appropriate:
	$element->parentElement->dataset->invalidMessage = $errorMessage;
}

The last line of the foreach loop sets the data-invalid-message attribute to the parent element of the invalid input. Typically this would be a <label> element, and outputting the error message can be done using the following CSS:

label[data-invalid-message]::before {
	content: attr(data-invalid-message);
	color: red;
}

There are many ways the error message can be output to the page. Another method would be to create a new element and append it to the document in an appropriate location:

// Create a new <span> element, add "error" to the class attribute, and set the
// text content to the value of the matching error message:
$errorMessageElement = $document->createElement("span");
$errorMessageElement->classList->add("error");
$errorMessageElement->textContent = $errorMessage;
// Then insert the newly created error message span before the input element.
$element->before($errorMessageElement);

The procedure of adding the error message to the page is completely up to you, as every application is different and forms take many different shapes.