1

My form is like this

<form  data-mage-init='{"validation":{}}' id="donation-request-form" method="post" data-hasrequired="* Required Fields">
    <div class="row">
        <div class="col-lg-6 col-md-6 col-xs-12 row-padding">
                <span class="fname-icon"></span>
                <input type="text" class="form-control fname" id="first_name" name="first_name" placeholder="First Name" data-validate='{"required":true}'>
        </div>
        <div class="col-lg-6 col-md-6 col-xs-12 row-padding">
                    <input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name">
        </div>
    </div>
    <div class="form-button button-section">
        <input class="btn-orange" type="submit" value="Request Donation" onclick="SendForm()">
    </div>
</form>

This is my SendForm() function

<script type="text/javascript">
function SendForm() {       
    var customurl = "<?php echo $baseURL_l.'emails/index/index'?>";
    alert(customurl);
    jQuery.ajax({
    type : 'POST',
    url : customurl,
    data : jQuery('#donation-request-form').serialize(),
    success: function(msg){
        alert(msg);
    }
    });
}

If i click submit button without filling any values of the form it will redirect to the controller and after the form validation is happening.

I want to validate first and submit the form to controller second. I do not want to do any custom js validation.I want to use only magento validation.

8

Try this:

if (jQuery('#donation-request-form').valid()) {
    jQuery.ajax({
    type : 'POST',
    url : customurl,
    data : jQuery('#donation-request-form').serialize(),
    success: function(msg){
        alert(msg);
    }
    });
}
| improve this answer | |
4

I found a good way of form submission with AJAX while using magento2 default form validation which I would like to share with the community.

We simply use below code for form validation

require([‘jquery’,’mage/validation’], function($){

    var dataForm = $(‘#form-validate’);

    dataForm.mage(‘validation’, {});

});

We can extend this to :

require([‘jquery’,’mage/validation’], function($) {

  var dataForm = $(‘#form-validate’);

  dataForm.mage(‘validation’, {});

  $(‘button#submit-button’).click( function() { //can be replaced with any event   

    var status = dataForm.validation(‘isValid’); //validates form and returns boolean

    if(status) {
      console.log(‘form is validated’); //form is valid
      //Do the AJAX call here

    } else {

      console.log(‘form is not validated’); 

    }   

  });

});

You can find detail description in this link.

Hope this helps!!

| improve this answer | |

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.