1

I have added custom form in customer account navigation.

Looking for code to form validation.

is there anything like form-validate like in magento1?

I have used in magento1 like below.

var dataForm = new VarienForm('form-validate', true);

Like that anything is there in magento2? How can we do form validation in magento 2?

  • There are two types of forms in Magento2. And 2 types of validators. Forms that are generated with knockout|ui components (e.g. checkout) and forms that are normally generated (e.g my account if I'm not mistaken). This might help you as well. Check my answer on this question magento.stackexchange.com/questions/139711/… . Also look for validator.js files in your project you'll get a sense of what I'm talking about. – vitoriodachef Aug 3 '18 at 14:49
0

I have managed to add form validation to custom form by following code:

<form id="custom_form" action="" method="post">
    <input class="form-control" name="firstname" type="text" placeholder="" data-validate="{required:true}" /></div>
    <input class="form-control" name="middlename" type="text" placeholder="" /></div>
    <input class="form-control" name="lastname" type="text" placeholder="" data-validate="{required:true}" />
    <input class="form-control" name="email" type="email" placeholder="" data-validate="{required:true, 'validate-email':true}" />
    <button class="btn-confirm" type="submit">Submit</button>
</form>
<script type="text/x-magento-init">
// <![CDATA[
    {
        "#custom_form": {
            "validation": {}
        }
    }
// ]]>
</script>

You need to add data-validate to every input fields where you want validation like below which means value is required and also validate email validation:

data-validate="{required:true, 'validate-email':true}"
  • what should i add inside this object "validation": {} – Ahmad Elkenany Oct 15 '19 at 11:45
  • validation syntax – Ahmad Elkenany Oct 15 '19 at 11:46
  • dataForm.mage('validation', { "firstname": { required:true, 'letters-only':true } }); – Ahmad Elkenany Oct 15 '19 at 11:46
  • Is that syntax true – Ahmad Elkenany Oct 15 '19 at 11:47
  • firstname -> represent the id of the input – Ahmad Elkenany Oct 15 '19 at 11:48

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.