Server-side validation
There are many ways to implement server-side validation (one option is Magewire form validation).
One way to implement custom validation logic is by using form modifiers.
The most tricky thing about this is showing validation failures to the customer.
One convenient way is to do that is to hook into the existing JS form validation rule logic to display the error message using setAttribute
.
<?php
namespace Hyva\Example\Model\FormModifier;
use Hyva\Checkout\Model\Form\EntityFormInterface;
use Hyva\Checkout\Model\Form\EntityFormModifierInterface;
class AnotherCustomFieldFormModifier implements EntityFormModifierInterface
{
public function apply(EntityFormInterface $form): EntityFormInterface
{
$form->registerModificationListener(
'validate-input-example',
'form:build', // use form:build so the value will be validated on preceding and subsequent requests
[$this, 'validateMyFormField']
);
return $form;
}
public function validateMyFormField(EntityFormInterface $form)
{
$myField = $form->getField('my_field');
if (! $myField->getValue()) {
return;
}
$result = $this->validate($myField)
if (!$result->isValid()) {
$myField->setAttribute('data-magewire-is-valid', '0');
$myField->setAttribute('data-msg-magewire', $result->getMessage());
}
}
private function validate($value)
{
// validate $value
}
}
Please note that even though in this example the validation happens server side, the restriction on checkout navigation and order placement is only JavaScript based.
Be sure to also validate all user input server side before the order is placed, for example, using a plugin on \Hyva\Checkout\Model\Magewire\Payment\PlaceOrderServiceInterface::placeOrder
.