How to Add JavaScript Form Validation in Hyvä Magento 2

Hyvä themes primarily use HTML 5 browser validation. However, there are times when you need more control like displaying custom error messages or implementing complex validation logic. 

Hyvä provides a powerful and flexible JavaScript form validation library built on Alpine.js. This guide provides a step-by-step to add JavaScript form validation in Hyvä Magento 2 website.

Step-by-Step Tutorial: JavaScript Form Validation in Hyvä Theme

You can prepare your validation form using these three steps in your Hyvä:

1. Activate the JS Validation Library

First load the required JavaScript on the relevant pages to integrate form validation.

This can be achieved by applying the hyva_form_validation layout handle within your layout XML file.

XML

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block name="my-custom-form" template="My_Module::form.phtml">
                <arguments>
                    <argument name="hyva_form_validation" xsi:type="boolean">true</argument>
                </arguments>
            </block>
        </referenceContainer>
    </body>
</page>

2. Initialize the Alpine.js Component

Utilize Alpine.js to initialize the validation component for your form element. Make sure your basic HTML form contains the below code.

apply x-data="hyva.formValidation($el)".

HTML

<form x-data="hyva.formValidation($el)" @submit="onSubmit">
    </form>


If you require adding custom logic then you will need to integrate the validation component into your Alpine component.

HTML

<form x-data="{...hyva.formValidation($el), myCustomProperty: 'value'}" @submit="onSubmit">
    </form>

3. Trigger Validation Events

The library offers a streamlined approach to form validation with Alpine.js events integration. Allowing developers to leverage the event-driven architecture of Alpine.js for handling form submissions and validating user input. 

When a form is submitted, or when specific input fields are interacted with, the library hooks into standard Alpine.js events, enabling real-time validation feedback and ensuring data integrity before processing.

  • Form Submission: To validate all fields upon form submission, use @submit=”onSubmit” on the <form> tag. The library automatically adds the novalidate attribute to prevent browser validation conflicts.
  • Individual Fields: For real-time validation as a user interacts with a field, apply an event like @change=”onChange” directly to the <input> element.
HTML

<div class="field field-reserved">
    <label for="email">Email</label>
    <input type="email" name="email" id="email"
          @change="onChange"
          required>
</div>

It’s recommended to use the field-reserved classes on the wrapper div to avoid layout shifts when error messages appear.

Defining Validation Rules

You can define validation rules in two ways:

  • HTML5 Attributes: The library automatically picks up native browser constraints like required, minlength, maxlength, pattern, min, max, and step.
  • data-validate Attribute: For custom rules or multiple rules, use the data-validate attribute.

Important: The value must be a valid JSON object (keys and string values in double quotes).

Here is an example combining both methods:

HTML

<div class="field field-reserved">
    <label for="username">Username</label>
    <input type="text" id="username" name="username"
          required
          data-validate='{"minlength": 5, "maxlength": 15}'
          data-msg-minlength="Username must be at least %0 characters long."
          class="input-text">
</div>

You can use the data-msg-minlength attribute to customize the default validation message 

Also, it allows to override any validator’s default message by following the format data-msg-VALIDATOR_NAME.

 The %0 placeholder will automatically be replaced with the rule’s argument (e.g., “5”).

Available Built-in Validators

Hyvä includes a set of common validators out of the box.

NameUsage ExamplesNote
requiredrequired or data-validate='{“required”: true}’Uses the browser’s constraint API.
minlengthminlength=”2″ or data-validate='{“minlength”: 2}’Uses the browser’s constraint API on text inputs.
maxlengthmaxlength=”8″ or data-validate='{“maxlength”: 8}’Uses the browser’s constraint API on text inputs.
patternpattern=”[A-Z]{5}” or data-validate='{“pattern”: “[A-Z]{5}”}’Uses the browser’s constraint API.
minmin=”1″ or data-validate='{“min”: 1}’For number inputs.
maxmax=”10″ or data-validate='{“max”: 10}’For number inputs.
stepstep=”2″ or data-validate='{“step”: 2}’For number inputs.
emailtype=”email” or data-validate='{“email”: true}’Uses Magento’s email validation regex.
passworddata-validate='{“password”: true}’Uses Magento’s password validation regex.
equalTodata-validate='{“equalTo”: “#password”}’Compare the field’s value to another field’s value using a selector.

Implementing JavaScript form validation in the Hyvä theme not only enhances user experience but also ensures data accuracy and security in your Magento 2 store. 

With Hyvä’s lightweight and performance-focused architecture, you can easily integrate custom validation logic while keeping your site fast and responsive. 

Whether it’s improving checkout forms or contact forms, proper validation helps prevent errors and builds customer trust. 

Start implementing these best practices to make your Hyvä-based Magento store more reliable and user-friendly.

Sanjay Jethva

Article by

Sanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for...