Home > OS >  Form validation in ajax requires only the first input in the class to be filled
Form validation in ajax requires only the first input in the class to be filled

Time:08-01

I'm trying to do validation for my form. I want to make it so if any item with class "required" is empty the form won't be submitted. Right now this is the case only for the first item in the class. For example, I have 3 inputs with class "required" - name, surname, address. The form is sent when I fill in only name, but surname and address are still empty.

Similar problem with $('.required').addClass('error'); - it should have a red border only in the empty field, but it has it on all the fields with "required" class. Is there a way to fix it?

$(function() {

  $('#form').on('submit', function(e) {

    e.preventDefault();

    if ($('.required').val() === '') {
      $('#add').addClass('error');
      $('.required').addClass('error');
      $('#text').html("Fill in the form.");;
    } else {
      $.ajax({
        type: "post",
        url: 'php/php.php',
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function() {
          document.getElementById("text").innerHTML = "success";
          document.getElementById("add").style.border = "2px solid green";
        },
        error: function() {
          document.getElementById("text").innerHTML = "error";
          document.getElementById("add").style.border = "2px solid red";
        }
      });
    }

  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p id="text">Placeholder</p>

<form id="form" method="POST" action="php/php.php">

  <input type="text" name="Name" id="name" ><br>
  <ol>
    <li>
      <input type="number" name="x1" >
      <input type="text" name="xa1" >
      <be>
    </li>
    <li>
      <input type="number" name="x2">
      <input type="text" name="xa2"><br>
    </li>

    <input type="submit" name="Add" id="add">

</form>

CodePudding user response:

$('.required') return a collection of jQuery DOM element, so you need to loop through this collection. Try this solution

    $(function () {

        $('#form').on('submit', function (e) {

            e.preventDefault();
            let alllfine = true;
            $('.required').each(function () {
                if ($(this).val() == '') {
                    $('#text').html("Fill in the form.");
                    $('#add').addClass('error');
                    $(this).addClass('error');
                    $(this).css('border', '1px solid red');
                    alllfine = false;
                } else {
                    $(this).css('border', '1px solid black');
                }
            })
            if (alllfine) {
                $.ajax({
                    type: "post",
                    url: 'php/php.php',
                    data: new FormData(this),
                    processData: false,
                    contentType: false,
                    success: function () {
                        document.getElementById("text").innerHTML = "success";
                        document.getElementById("add").style.border = "2px solid green";
                    },
                    error: function () {
                        document.getElementById("text").innerHTML = "error";
                        document.getElementById("add").style.border = "2px solid red";
                    }
                });
            }

        });

    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p id="text">Placeholder</p>

<form id="form" method="POST" action="php/php.php">

    <input type="text" name="Name" id="name" ><br>
    <ol>
        <li>
            <input type="number" name="x1" >
            <input type="text" name="xa1" >
            <be>
        </li>
        <li>
            <input type="number" name="x2">
            <input type="text" name="xa2"><br>
        </li>

        <input type="submit" name="Add" id="add">

</form>

CodePudding user response:

You need to test each of the fields returned

const $req = $('.required');
const valid = $req.filter(function() { 
  const thisValid = this.value.trim() !== "";
  $(this).toggleClass('error',!thisValid);
  return thisValid }).length === $req.length;
if (valid) {
  // ajax here
}

But why not just use required attribute?

$(function() {

  $('#form').on('submit', function(e) {
   // we will only see this if required fields are filled in
   console.log("ajax here")
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p id="text">Placeholder</p>

<form id="form" method="POST" action="php/php.php">

  <input type="text" name="Name" id="name" ><br>
  <ol>
    <li>
      <input type="number" name="x1" required>
      <input type="text" name="xa1" required>
    </li>
    <li>
      <input type="number" name="x2">
      <input type="text" name="xa2"><br>
    </li>
  </ol>
  <input type="submit" name="Add" id="add">

</form>

  • Related