Magento2 Form Validation – Minimum and Maximum Length

form-validationformsmagento2validation

I'm trying to add some of the predefined validation to a form element but currently am failing. As fas as I can tell, all the validation rules can be added via classes, but no where does it say how to set paramaters for some of the rules. IE: max length.

Here's what I currently have that is not working (I've stripped out some of the non-pertinent attributes. I'm trying to set a minimum of 7 characters on the input.

<input name="telephone" id="telephone" data-validate="{required:true}" class="validate-length minimum-length-7 maximum-length-20 input-text" type="text" />

Thanks for your help

Best Answer

Your code is totally right.

Both minimum and maximum need to be set with minimum-length-[0-9]+$ and maximum-length-[0-9]+$

What you are missing is to update the data-validate attribute by replacing:

{required:true}

With:

{required:true, 'validate-length':true}

Also you'll have to ensure that your custom form is validated via JavaScript with one of the following methods:

Direct JS

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

HTML attribute

By adding the following attribute to your form tag:

data-mage-init='{"validation": {}}'

Using RequireJS

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

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

});
</script>