Add validation into custom form Magento 2

Written by Mahesh Makwana

Mar 27, 2021

Add validation into custom form Magento 2

How to add validation into custom form Magento 2?

In module development, we need to create some forms, so the data in the form should be correct. Magento 2 provides to add default validation in custom forms We check whether the form data is valid.

There are different ways to use form validation in Magento 2

1) Using the data-mage-init attribute

<form id="my-form" data-mage-init='{"validation": {}}'>
    ...
</form>

2) Using the text/x-magento-init script type tag

<script type="text/x-magento-init">
    {
        "#form-id": {
            "validation": {}
        }
    }
</script>

3) Using the data-validate attribute

<input id="field-1" ... data-validate='{"required":true}'/>

4) Using As an attribute

<input id="field-1" ... required="true"/>

5) Using As a class name

<input id="field-1" ... class="input-text required-entry"/>

6) Using require js

<script type="text/javascript">
    require([
        'jquery',
        'mage/mage'
    ], function($){

       var dataForm = $('#form-id');
       dataForm.mage('validation', {});

    });
</script>

Examples of validating the form fields are given below.

<form class="form" id="my-form" method="post" data-mage-init='{"validation":{"rules": {"field-4": {"required":true}}}}'><!-- Using the data-mage-init attribute -->
    <fieldset class="fieldset">
        <div class="field name required">
            <label class="label" for="field-1"><span>Field 1 (using data-validate)</span></label>
            <div class="control">
                <input name="field-1" id="field-1" title="Field 1" value=""  class="input-text" type="text" data-validate='{"required":true, "url": true}'/>
            </div>
        </div>
        <div class="field name required">
            <label class="label" for="field-2"><span>Field 2 (using attribute)</span></label>
            <div class="control">
                <input name="field-2" id="field-2" title="Field 2" value="" class="input-text" type="text" required="true"/>
            </div>
        </div>
        <div class="field name required">
            <label class="label" for="field-3"><span>Field 3 (using classname)</span></label>
            <div class="control">
                <input name="field-3" id="field-3" title="Field 3" value="" type="text" class="input-text required-entry"/>
            </div>
        </div>
        <div class="field name required">
            <label class="label" for="field-4"><span>Field 4 (using data-mage-init)</span></label>
            <div class="control">
                <input name="field-4" id="field-4" title="Field 4" value="" class="input-text" type="text"/>
            </div>
        </div>
    </fieldset>
    <div class="actions-toolbar">
        <div class="primary">
            <button type="submit" title="Submit" class="action submit primary">
                <span>Submit</span>
            </button>
        </div>
    </div>
</form>

// Using the text/x-magento-init script type tag

<script type="text/x-magento-init">
    {
        "#my-form": {
            "validation": {}
        }
    }
</script>

/// Using require js

<script type="text/javascript">
    require([
        'jquery',
        'mage/mage'
    ], function($){

       var dataForm = $('#my-form');
       dataForm.mage('validation', {});

    });
</script>

Here we show you all the valid ways to use form validations. So it’s not necessary to use this all way into the same form. You can select one way and implement it into your custom form.

There are not lots of validation available in magento 2. so here we show some validation error messages below:

required-entry: This is a required field.

validate-alphanum-with-spaces: Please use only letters (a-z or A-Z), numbers (0-9), or spaces only in this field.

phoneUK: Please specify a valid phone number

validate-email: Please enter a valid email address (Ex: johndoe@domain.com).

ipv4: Please enter a valid IP v4 address.

checked: This is a required field.

validate-select: Please select an option.

ipv6: Please enter a valid IP v6 address.

time: Please enter a valid time, between 00:00 and 23:59

validate-number: Please enter a valid number in this field.

validate-phoneLax: Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.

dateITA: Please enter a correct date

validate-xml-identifier: Please enter a valid XML-identifier (Ex: something_1, block5, id-4).

validate-clean-url: Please enter a valid URL. For example http://www.example.com or www.example.com.

validate-admin-password: Please enter 7 or more characters, using both numeric and alphabetic.

validate-no-html-tags: HTML tags are not allowed.

validate-integer: Please enter a valid integer in this field.

validate-data: Please use only letters (a-z or A-Z), numbers (0-9) or underscore (_) in this field, and the first character should be a letter.

validate-cc-ukss: Please enter issue number or start date for switch/solo card type.

min-words: Please enter at least {0} words.

alphanumeric: Letters, numbers, spaces or underscores only please

validate-identifier: Please enter a valid URL Key (Ex: “example-page”, “example-page.html” or “anotherlevel/example-page”).

validate-street: Please use only letters (a-z or A-Z), numbers (0-9), spaces and “#” in this field.

validate-zip-international: Please enter a valid zip code.

validate-date: Please enter a valid date.

validate-greater-than-zero: Please enter a number greater than 0 in this field.

validate-digits: Please enter a valid number in this field.

validate-ssn: Please enter a valid social security number (Ex: 123-45-6789).

not-negative-amount: Please enter positive number in this field.

validate-max-size: The file you are trying to upload exceeds the maximum file size limit.

validate-fax: Please enter a valid fax number (Ex: 123-456-7890).

validate-if-tag-script-exist: Please use tag SCRIPT with SRC attribute or with proper content to include JavaScript to the document.

min_text_length: Please enter more or equal than {0} symbols.

validate-date-au: Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.

mobileUK: Please specify a valid mobile number

letters-with-basic-punc: Letters or punctuation only please

validate-number-range: The value is not within the specified range.

phoneUS: Please specify a valid phone number

date_range_max: The date is not within the specified range.

validate-range: The value is not within the specified range.

vinUS: The specified vehicle identification number (VIN) is invalid.

range-words: Please enter between {0} and {1} words.

validate-zip-us: Please enter a valid zip code (Ex: 90602 or 90602-1234).

validate-emails: Please enter valid email addresses, separated by commas. For example, johndoe@domain.com, johnsmith@domain.com.

validate-css-length: Please input a valid CSS-length (Ex: 100px, 77pt, 20em, .5ex or 50%).

zip-range: Your ZIP-code must be in the range 902xx-xxxx to 905-xx-xxxx

validate-phoneStrict: Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.

letters-only: Letters only please

max_text_length: Please enter less or equal than {0} symbols.

validate-not-negative-number: Please enter a number 0 or greater in this field.

validate-per-page-value-list: Please enter a valid value, ex: 10,20,30

no-whitespace: No white space please

validate-state: Please select State/Province.

validate-url: Please enter a valid URL. Protocol is required (http://, https:// or ftp://).

date_range_min: The date is not within the specified range.

validate-digits-range: The value is not within the specified range.

greater-than-equals-to: Please enter a value greater than or equal to {0}.

validate-no-empty: Empty Value.

validate-zero-or-greater: Please enter a number 0 or greater in this field.

validate-cc-number: Please enter a valid credit card number.

validate-emailSender: Please enter a valid email address (Ex: johndoe@domain.com).

validate-new-password: Please enter 6 or more characters. Leading and trailing spaces will be ignored.

validate-customer-password: Minimum length of this field must be equal or greater than %1 symbols. Leading and trailing spaces will be ignored.

validate-password: Please enter 6 or more characters. Leading and trailing spaces will be ignored.

less-than-equals-to: Please enter a value less than or equal to {0}.

validate-currency-dollar: Please enter a valid $ amount. For example $100.00.

time12h: Please enter a valid time, between 00:00 am and 12:00 pm

validate-alphanum: Please use only letters (a-z or A-Z) or numbers (0-9) in this field. No spaces or other characters are allowed.

validate-item-quantity: We don\’t recognize or support this type of file extension in Magento 2.

validate-code: Please use only letters (a-z), numbers (0-9) or underscore (_) in this field, and the first character should be a letter.

max-words: Please enter {0} words or less.

stripped-min-length: Please enter at least {0} characters

validate-alpha: Please use letters only (a-z or A-Z) in this field.

pattern: Invalid format.

integer: A positive or negative non-decimal number please

And there is so much validation in magento 2. Above are commonly used validation so it helps you.

I hope this helps you. For any doubts regarding this topic, please write your doubts in the comments section.

Mahesh Makwana

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP