-
Notifications
You must be signed in to change notification settings - Fork 0
Quick start guide
In this guide we will validate one simple form, stop invalid data on the server, and add an error message back into the document.
The aim is not to cover every feature yet. It is to get the full request/validate/respond loop working first.
composer require phpgt/domvalidation<form id="signup" method="post">
<label>
<span>Email address</span>
<input name="email" type="email" required />
</label>
<label>
<span>Password</span>
<input name="password" type="password" minlength="12" required />
</label>
<button name="do" value="register">Create account</button>
</form>At this point the browser already knows some useful things:
- the email must look like an email address
- both fields are required
- the password must be at least twelve characters long
DomValidation will reuse those same rules on the server.
use GT\Dom\HTMLDocument;
use GT\DomValidation\ValidationException;
use GT\DomValidation\Validator;
$document = new HTMLDocument($html);
$form = $document->querySelector("#signup");
$validator = new Validator();
try {
$validator->validate($form, $_POST);
}
catch(ValidationException) {
// We will display the errors in the next step.
}
echo $document; // display the page to the browser, unchanged, or with errors appended.If all submitted values are valid, validate() returns normally. If any field is invalid, it throws ValidationException.
catch(ValidationException) {
foreach($validator->getLastErrorList() as $name => $message) {
$field = $form->querySelector("[name='$name']");
$field?->parentElement?->dataset->validationError = $message;
}
}Now the relevant label elements have a data-validation-error attribute. We can show that with CSS:
label[data-validation-error]::before {
content: attr(data-validation-error);
display: block;
color: crimson;
font-weight: bold;
}This keeps invalid input out of the rest of the application logic.
try {
$validator->validate($form, $_POST);
}
catch(ValidationException) {
foreach($validator->getLastErrorList() as $name => $message) {
$field = $form->querySelector("[name='$name']");
$field?->parentElement?->dataset->validationError = $message;
}
echo $document;
return;
}
// Continue with valid input only.At this point:
- the browser still handles client-side validation as usual
- the server re-checks the same form constraints
- the error messages come back from the validator already matched to field names
- invalid data stops before it reaches the rest of the application
Note
In WebEngine, this same pattern usually sits inside a do_*() function. The framework already provides the current HTMLDocument and request input object, so the main job is just to find the form and call validate().
From here, read the Default validation rules so we know exactly which built-in constraints are currently supported.
DomValidation is a separately maintained component of PHP.GT WebEngine.