Client-side field validation
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.
This document is about client side validation.
Setting JavaScript validation rules on a field can be done with the method setValidationRule
.
Here are some examples of how it can be used
$myField->setValidationRule('maxlength', 10); // data-validate='{"maxlength": 10}'
$myField->setValidationRule('required'); // data-validate='{"required": true, "maxlength": 10}'
Adding a custom validation rule
To declare a custom JS validation rule, set it on the field like above, and then render a template on the checkout to add the custom rule.
Set the rule on the field
Render the template for the rule
In a hyva_checkout_index_index.xml
layout file, add:
<referenceContainer name="before.body.end">
<block name="my-js-validation-rule" template="Hyva_Example::my-validation-rule.phtml"/>
</referenceContainer>
Add the rule logic
And then declare the rule in the template. For example:
<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>