Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have a billing form, but the issue is that it is not validating correctly. I want that when user clicks proceed payment, it must ensure that all fields are inserted, thereafter they can proceed to the next page.

What I have tried:

HTML
<pre><div class="form-outline mb-4">
    <input type="text" id="form7Example1" class="form-control" />
    <label class="form-label" for="form7Example1">First name</label>
</div>
<div class="form-outline mb-4">
    <input type="text" id="form7Example2" class="form-control" />
    <label class="form-label" for="form7Example2">Last name</label>
</div>
<div class="form-outline mb-4">
    <input type="text" id="form7Example3" class="form-control" />
    <label class="form-label" for="form7Example3">Company name</label>
</div>
<div class="form-outline mb-4">
    <input type="text" id="form7Example4" class="form-control" />
    <label class="form-label" for="form7Example4">Address</label>
</div>
<div class="form-outline mb-4">
    <input type="email" id="form7Example5" class="form-control" />
    <label class="form-label" for="form7Example5">Email</label>
</div>
<div class="form-outline mb-4">
    <input type="number" id="form7Example6" class="form-control" />
    <label class="form-label" for="form7Example6">Phone</label>
</div>
<div class="form-outline mb-4">
    <textarea class="form-control" id="form7Example7" rows="4"></textarea>
    <label class="form-label" for="form7Example7">Additional information</label>
</div>
<button id="proceed-to-payment" class="btn btn-block btn-primary my-3 py-3">Proceed To Payment</button>


//jquery code
jquery
/***
@author:Gcobani Mkontwana
@date:10/05/2025
@Script handles billing validation address before proceed payment.
**/
$(document).ready(function() {
  // Function to validate and update field borders
  function validateAndUpdateField(fieldId) {
    const $field = $(fieldId);
    const fieldValue = $field.val().trim();
    if (fieldValue === '') {
      // Field is empty, set border color to red
      $field.css('border-color', 'red');
    } else {
      // Field is filled, set border color to green
      $field.css('border-color', 'green');
    }
  }

  // Event listener for input fields
  $('.form-control').on('input', function() {
    validateAndUpdateField($(this));
  });

  // Event listener for the "Proceed To Payment" button
  $('#proceed-to-payment').click(function() {
    // Loop through all input fields and validate them
    let isValid = true;
    const requiredFields = ['#form7Example1', '#form7Example2', '#form7Example4', '#form7Example5', '#form7Example6'];
    requiredFields.forEach(function(fieldId) {
      validateAndUpdateField(fieldId);
      const fieldValue = $(fieldId).val().trim();
      if (fieldValue === '') {
        isValid = false;
      }
    });

    // If any field is empty, prevent form submission
    if (!isValid) {
      alert('Please fill in all required fields.');
      return false;
    }

    // Proceed with payment if all required fields are filled
    alert('Payment successful!'); // Replace with your actual payment logic
  });
});


JavaScript
<script>
document.getElementById("proceed-to-payment").addEventListener("click", function () {
    // Get cart data from the PHP-generated HTML
    var cartItems = <?php echo json_encode($cartItems); ?>;
    var subtotal = <?php echo $totalPrice; ?>;
    var shippingCost = <?php echo $shippingCost; ?>;
    var totalPrice = subtotal + shippingCost;
    
    // Prepare data to send to the payment_integration page
    var dataToSend = {
        cartItems: cartItems,
        totalPrice: totalPrice
    };

    // Make an AJAX request to the payment_integration page
    $.ajax({
        type: "POST",
        url: "payment_integration.php",
        data: JSON.stringify(dataToSend),
        contentType: "application/json",
        success: function (response) {
            // Redirect to the payment page
            var redirectUrl = "payment_integration.php?cartData=" + encodeURIComponent(JSON.stringify(dataToSend));
            window.location.href = redirectUrl;
            console.log("cartitem", dataToSend);
        },
        error: function (xhr, status, error) {
            // Handle errors if necessary
            console.error(error);
        }
    });
});
Posted
Updated 5-Oct-23 6:00am
v2
Comments
Richard MacCutchan 5-Oct-23 11:58am    
You have not explained what the problem is. But I notice that #form7Example3 and #form7Example7 are missing from requiredFields.
Gcobani Mkontwana 5-Oct-23 12:16pm    
@Richard MacCutchan, the problem is form itself is not validating well instead its sending an alert and not allowing user to first insert data thereafter once all this information is given it can be redirect to payment page hope make sense now.
[no name] 5-Oct-23 14:07pm    
Do it on the server. If too many errors, blank out the whole form ... someone is trying to hack you. The banks will do it with a 10 page application if you don't know "their" format for a phone number ... so why not you?

1 solution

The problem lies in your 'validateAndUpdateField' function that does not check wheteher all fields have been filled or not, change it to -

JavaScript
$(document).ready(function() {
  // ... Existing code ...

  // Event listener for the "Proceed To Payment" button
  $('#proceed-to-payment').click(function() {
    // Validate all input fields
    let isValid = true;
    const requiredFields = ['#form7Example1', '#form7Example2', '#form7Example4', '#form7Example5', '#form7Example6'];

    for (const fieldId of requiredFields) {
      validateAndUpdateField(fieldId);
      const fieldValue = $(fieldId).val().trim();
      if (fieldValue === '') {
        isValid = false;
      }
    }

    // If any field is empty, prevent form submission
    if (!isValid) {
      alert('Please fill in all required fields.');
      return false;
    }

    // Proceed with payment if all required fields are filled
    // Redirect to the payment page here or perform necessary actions
    alert('Payment successful!'); // Replace with your actual payment logic
  });
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900