Form validations
Client-side
Do not rely exclusively on client-side validation!
It is trivial to bypass browser-based form validation for experienced web developers. In-browser validation should be used only to give visitors fast feedback. Always use server-side validation as the primary way to check user input.
Adding custom validation rules is pretty common. In Hyvä-Checkout, both client-side JavaScript validation can be used (via the Hyvä validation library), or server-side Magewire-based validation.
Setting JavaScript validation rules for a field is achieved through the utilization of the setValidationRule()
method.
// Results in: data-validate='{"maxlength": 10}'
$myField->setValidationRule('maxlength', 10);
// Results in: data-validate='{"required": true, "maxlength": 10}'
$myField->setValidationRule('required');
Custom validation rules
To define a custom JavaScript validation rule, apply it to the field as shown above. Subsequently, render a template on the checkout page to incorporate the custom rule.
1. Set the rule on the field
You can specify validation rules during various stages, including utilizing a form modifier or incorporating them during
form construction within the populate
method.
2. Render the template for the rule
Next, to ensure that custom validation rules reside within their own dedicated PHTML file, we need to register
the PHTML file within a container that automatically renders it on the page. This can be achieved by utilizing the
hyva_checkout_index_index.xml
layout file.
<referenceContainer name="before.body.end">
<block name="my-js-validation-rule"
template="My_Example::my-validation-rule.phtml"
/>
</referenceContainer>
3. Declare the rule in the template.
Finally, the rule must be written and incorporated into the Advanced Form Validation.
<script>
(() => {
if (hyva && hyva.formValidation) {
const isPrime = n => {
if (n <= 1) return false;
for (let i = 2; i < Math.sqrt(n), i++) {
if (n % i === 0) return false
}
return true;
}
hyva.formValidation.addRule('example', (value, options, field, context) => {
const el = field.element;
if (options && el.value.length && context.fields.country_id) {
const country = context.fields.country_id.element.value;
if (country === 'DE' && ! isPrime(parseInt(el.value))) {
return '<?= $escaper->escapeJs(__('Please enter a prime number.')) ?>'
}
}
return true;
});
}
})()
</script>