0

I'm trying to validate the input fields of a form, but I have an issue that when the validations are failing, my form is submitted anyway. I want to prevent the submission until validations pass.

<form method="post" action = "withdrawSubmit" id="withdraw_form">
  <input type="hidden" name="_token" value="{{ csrf_token() }}">

  <div class="form-group row">
    <div class="col-sm-12">
      <label class="col-sm-2 text-right">Address:</label>
      <input type="text" name="address" class="col-sm-10" id="address" value="">
    </div>
  </div>

  <div class="form-group row">
    <div class="col-sm-12" >
      <label class="col-sm-2 text-right">Amount:</label>
      <input type="number" step="any" name="amount" onchange="validateAmount()" class="col-sm-10" id="amount" value="">
      <span id="err_msg" style="color: red;"></span>
    </div>
  </div>
  <button type="submit" class="btn btn_wthdraw btn-primary " id="btn" >Withdraw</button>
</form>

validateAmount Method:

 function validateAmount(){
    var amount = document.getElementById("amount").value;
    var validationFailed = false;
    $.ajax({
          url: "{{url('getAmount')}}", 
          type: "GET",
          dataType: "json",
          success: function(result){
              var res = parseInt(result.BTC);
              if(amount > res)
              {
                $("#err_msg").html('Number should be less than to available amount');
                return false;
              }else{
                $("#err_msg").html(' ');
                return true;
              }

          }
    });
}

Please help me to get this.Any help will be appreciated. Thanks in advance.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
user6891871
  • 164
  • 1
  • 3
  • 17
  • 2
    do all the validations in the `onsubmit` of the form rather than `onchange` of the field and if it passes successfully, you can make the ajax call – Varun Sharma Jan 12 '18 at 06:12
  • 1
    Just do a listener `$.('#withdraw_form').on('submit',function(e){});` then use `e.preventDefault();` to stop the submission. Then validate, then you can submit to ajax if successful. – Rasclatt Jan 12 '18 at 06:13
  • 1
    You need to disable the submit button and enable it here: `}else{ $("#err_msg").html(''); $("#btn").prop("disabled",false); }` – mplungjan Jan 12 '18 at 06:15

0 Answers0