Magento 2 – How to Perform Form Validation

customerform-validationforms

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?

Best Answer

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}"