2

I'm using Laravel JsValidation, JsValidation working properly with other forms, but because I should submit the form with Ajax, JsValidation is not working properly, and form submitted.

$validator = JsValidation::make($rules);

and in view

{!!$validator!!}
jones
  • 1,423
  • 3
  • 35
  • 76
  • Is this the library that you're using https://github.com/proengsoft/laravel-jsvalidation ? – Lance Pioch Apr 03 '16 at 20:36
  • `JsValidation is not working properly` is too vague, can you elaborate your problem. – Gaurav Dave Apr 05 '16 at 05:20
  • @GauravDave Suppose I have a form that should be submitted with ajax, I have passed the validation rules to `JsValidator`, now because of submit of form with ajax, `JsValidator` can't prevent from submit of form, and the form is submitted. – jones Apr 05 '16 at 06:14

2 Answers2

0

Since the validation call is asynchronous, mark that as synchronous by doing:

async: false

[optional] and to prevent form submit default functionality, do:

e.preventDefault();

on submit button click. After doing validation you'll get response based on that response, you can allow form to submit or not.

Simple Code Snippet:

$("#form-submit").on('submit', function(){
        var errorMsg = 'Please provide your correct information.';
        $(".errorMsg ").text("");
        var txtName = $("input#txtName").val();

        var responseStatus = false;
        var userData = {
            'name' : txtName
        };

        $.ajax({
           type: 'POST',
           url: '/validate-data',
           async: false,
           data: userData,
           success: function(result){
                if(result.status === true){
                    responseStatus = true;
                } else {
                    responseStatus = false;
                    errorMsg = result.message;
                    $(".errorMsg ").text(errorMsg);
                    return false;
               }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                  alert('Oops! Something went wrong. Please try again.');                     return false;
             }
         });

     if(responseStatus === false){
          return false;
     } else {
          return true;
     }
});

See, if that helps.

Gaurav Dave
  • 6,838
  • 9
  • 25
  • 39
0

Try to use this snippet:

$('form').on('submit', function() {
  if($(this).valid()) {
    // do your ajax stuff here
  }
  return false;
});
gaalgergely
  • 113
  • 10