27

is there a overview for the new form validation attributes in Magento 2?

35

You can add class for validation in Magento 2. See example bellow. There is almost 72 rules (validation class) you can use:

$fieldset->addField(
    'email_from',
    'text',
    ['name' => 'email_from', 'label' => __('Email From'), 'title' => __('Email From'), 'required' => true, 'class' => 'validate-email']
);

See blog for list of available rules for more info:

Here is list of validations classes rules supported by magento 2. You just need to add css class for the rule to apply.

min_text_length
max_text_length
max-words
min-words
range-words
letters-with-basic-punc
alphanumeric
letters-only
no-whitespace
zip-range
integer
vinUS
dateITA
dateNL
time
time12h
phoneUS
phoneUK
mobileUK
stripped-min-length
email2
url2
credit-card-types
ipv4
ipv6
pattern
validate-no-html-tags
validate-select
validate-no-empty
validate-alphanum-with-spaces
validate-data
validate-street
validate-phoneStrict
validate-phoneLax
validate-fax
validate-email
validate-emailSender
validate-password
validate-admin-password
validate-url
validate-clean-url
validate-xml-identifier
validate-ssn
validate-zip-us
validate-date-au
validate-currency-dollar
validate-not-negative-number
validate-zero-or-greater
validate-greater-than-zero
validate-css-length
validate-number
validate-number-range
validate-digits
validate-digits-range
validate-range
validate-alpha
validate-code
validate-alphanum
validate-date
validate-identifier
validate-zip-international
validate-state
less-than-equals-to
greater-than-equals-to
validate-emails
validate-cc-number
validate-cc-ukss
required-entry
checked
not-negative-amount
validate-per-page-value-list
validate-new-password
validate-item-quantity
equalTo
  • 1
    is there any example how to use pattern? tnx – Antonio Pedicini Sep 27 '17 at 8:53
29

There are 3 different ways to use form validation in magento 2

To enable javascript validation use following code in your template

<form class="form" id="custom-form" method="post" autocomplete="off">
 <fieldset class="fieldset">
     <legend class="legend"><span><?php echo __('Personal Information') ?></span></legend><br>
      <div class="field required">
          <label for="email_address" class="label"><span><?php echo __('Email') ?></span></label>
          <div class="control">
              <input type="email" name="email" id="email_address" value="" title="<?php echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true}">
          </div>
      </div>
 </fieldset>
 <div class="actions-toolbar">
      <div class="primary">
          <button type="submit" class="action submit primary" title="<?php  echo __('Submit') ?>"><span><?php echo __('Submit') ?></span></button>
      </div>
  </div>
</form>

1

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

2

<form data-mage-init='{"validation": {}}' class="form" id="custom-form" method="post" autocomplete="off">

3

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

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

});
</script>

*custom-form is form id you can replace it with your form id

List of form validation rules

To wrap up this article, a list of validation rule names is provided here as a quick reference toward the official documentation:

Magento rules:

validate-no-html-tags

validate-select

validate-no-empty

validate-alphanum-with-spaces

validate-data

validate-street

validate-phoneStrict

validate-phoneLax

validate-fax

validate-email

validate-emailSender

validate-password

validate-admin-password

validate-customer-password

validate-url

validate-clean-url

validate-xml-identifier

validate-ssn

validate-zip-us

validate-date-au

validate-currency-dollar

validate-not-negative-number

validate-zero-or-greater

validate-greater-than-zero

validate-css-length

validate-number

required-number

validate-number-range

validate-digits

validate-digits-range

validate-range

validate-alpha

validate-code

validate-alphanum

validate-date

validate-date-range

validate-cpassword

validate-identifier

validate-zip-international

validate-one-required

validate-state

required-file

validate-ajax-error

validate-optional-datetime

validate-required-datetime

validate-one-required-by-name

less-than-equals-to

greater-than-equals-to

validate-emails

validate-cc-type-select

validate-cc-number

validate-cc-type

validate-cc-exp

validate-cc-cvn

validate-cc-ukss

validate-length

required-entry

not-negative-amount

validate-per-page-value-list

validate-per-page-value

validate-new-password

required-if-not-specified

required-if-all-sku-empty-and-file-not-loaded

required-if-specified

required-number-if-specified

datetime-validation

required-text-swatch-entry

required-visual-swatch-entry

required-dropdown-attribute-entry

Validate-item-quantity

validate-grouped-qty

validate-one-checkbox-required-by-name

validate-date-between

validate-dob

max-words

min-words

range-words

letters-with-basic-punc

alphanumeric

letters-only

no-whitespace

zip-range

integer

vinUS

dateITA

dateNL

time

time12h

phoneUS

phoneUK

mobileUK

stripped-min-length

email2

url2

credit-card-types

ipv4

ipv6

pattern

allow-container-className

jQuery rules:

required,

remote,

email,

url,

date,

dateISO,

number,

digits,

creditcard,

equalTo,

maxlength,

minlength,

rangelength,

range,

max,

min

refer http://inchoo.net/magento-2/validate-custom-form-in-magento-2/

8

In UI components it can be used by following sample config (Magento v2.2.0):

<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="general">
        <field name="priority" sortOrder="1000" formElement="input">
            <settings>
                <validation>
                    <rule name="not-negative-amount" xsi:type="boolean">true</rule>
                </validation>
                [...]
            </settings>
        </field>
    </fieldset>
</form>

See more examples in file:
vendor/magento/module-cms/view/adminhtml/ui_component/cms_page_form.xml

The validators list in UI Components it can be found in
vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js.

Just wrote this script to grab all keys with error messages for explanation:

  • 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:
    File you are trying to upload exceeds 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.
  • dateNL:
    Vul hier een geldige datum in.
  • 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 file extension type.
  • validate-code:
    Please use only letters (a-z), numbers (0-9) or underscore (_) in this field, and the first character should be a letter.
  • email2:
    Please enter a valid credit card number.
  • 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

The script:

declare -A list
key=''
while IFS= read -r line; do
#  echo "${line} -"
  if [ -z "${key:-}" ]; then
    # match validation key
    match=$(echo "${line}" | grep -Eo "^        ['\"]([A-Za-z0-9-]|_)+" | tr -d "' ")
    if [ -n "${match}" ]; then
      key=${match}
    fi
  else
    # match message
    match=$(echo "${line}" | sed -rn "s|.*\\$\.mage\.__[(]['\"](.*)['\"][)].*|\1|p")
    if [ -n "${match}" ]; then
      list[${key}]=${match}
      key=''
    fi
  fi
done < "${DOCROOT_DIR:-/var/www/html}/vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js"

for i in "${!list[@]}"
do
  printf "%s:\n    %s\n" "${i}" "${list[$i]}"
done
3

If you take reference of /customer/account/create page, you can see the following piece of code underneath the form:

<script>
require([
    'jquery',
    'mage/mage'
], function($){

    var dataForm = $('#form-validate');
    var ignore = null;

    dataForm.mage('validation', {
            ignore: ignore ? ':hidden:not(' + ignore + ')' : ':hidden'
        }).find('input:text').attr('autocomplete', 'off');

});
</script>

And if you check at form's input attributes, you can see Magento 1 like class attribute values along with new data-validate attribute. This can be the basis to step up.

Keys files for Validation:

  • Thx for the answer. I found the new attribute data-validate too, but it's interesting what validations are available. In my case I want to validate a Checkbox and a set of RadioButton – ClassMP Dec 28 '15 at 10:13
  • I want to apply server side validation in magento 2 can you pls share me any link or doc. – Khushbu_sipl Feb 20 '17 at 10:08
1

I have same requirement for Magento2 Form Validation and i did this code

First we will setup a test form

<!-- form tag -->
<form class="form" id="custom-form-id" method="post" autocomplete="off">
   <fieldset class="fieldset">
       <legend class="legend"><span><?php echo __('User Personal Information') ?></span></legend><br>
        <div class="field required">
            <!-- form field -->
            <label for="email_address" class="label"><span><?php echo __('Email') ?></span></label>
            <div class="control">
                <input type="email" name="email" id="email_address" value="" title="<?php echo __('Email') ?>" class="input-text" data-validate="{required:true, 'validate-email':true}">
            </div>
        </div>
   </fieldset>
   <!-- submit button -->
   <div class="actions-toolbar">
        <div class="primary">
            <button type="submit" class="action submit primary" title="<?php  echo __('Submit') ?>"><span><?php echo __('Submit') ?></span></button>
        </div>
    </div>
</form>

To enable javascript validation for Magento2 Form Validation

<!-- enable javascript validation for custom-form-id -->
<script type="text/x-magento-init">
    {
        "#custom-form-id": {
            "validation": {}
        }
    }
</script>

Reference :: http://www.onlinecode.org/magento2-form-validation-example/

1

When use UI components to make form, we could use the validation like below, it works in Magento 2.1.x, I doesn't test it in other version yet.

<field name="priority">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="dataType" xsi:type="string">text</item>
            <item name="label" xsi:type="string" translate="true">Priority</item>
            <item name="formElement" xsi:type="string">input</item>
            <item name="source" xsi:type="string">module_name</item>
            <item name="dataScope" xsi:type="string">priority</item>
            <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">true</item>
                <item name="validate-integer" xsi:type="boolean">true</item>
            </item>
        </item>
    </argument>
</field>

Notice the validation item, in it we could add validation rules, like required-entry, validate-integer etc.

<item name="validation" xsi:type="array">
     <item name="required-entry" xsi:type="boolean">true</item>
     <item name="validate-integer" xsi:type="boolean">true</item>
     <item name="validation_rule_name" xsi:type="boolean">true</item>
     ...
</item>

All validation rules you could find in file vendor/magento/module-ui/view/base/web/js/lib/validation/rules.js, like validate-date, validate-emails etc.

0

"no-whitespace" option does not work correctly (at least on Magento 2.1). It triggers an error message on any type of "space" character. Values "test me" and " test me " will return the same error.

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.