Search code examples
javascriptjqueryformsmern

Form validation before submit using jquery


I have list of options and I have to valid that at least there should be 4 options.

I have paste part of that form below:

$("#livechatform").validate({
  rules: {
    options[]: {
      required: true,
      minlength: 4
    }
  },
  messages: {
    options[]: {
      required: "Please enter at least 4 options",
      minlength: "Please enter at least 4 options"
    }
  },
  submitHandler: (form) => form.submit();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form class="custom-validation repeater" method="post" id="livechatform" enctype="multipart/form-data" action="/admin/poll/create">
  <div class="col-10">
    <input class="form-control" name="options[]" type="text" required>
  </div>
  
  <div class="d-flex flex-wrap gap-2 mt-3">
    <button type="submit" class="btn btn-primary waves-effect waves-light">
      Submit <span class="spinner-border spinner-border-sm"></span>
    </button>
    
    <button type="reset" class="btn btn-secondary waves-effect">
      Cancel
    </button>
  </div>
</form>

But It is not working. can someone help me How to valid that ?


Solution

  • First: you need to include the jQuery Validation Plugin


    In your JS code are two issues: The name of the input is a string, therefor it needs to be in quotes:

    'options[]': {...
    

    The semicolon at the end of your submitHandler is wrong - remove it. I found both issues, because i read the error messages in the console...

    Furthermore you need to define indexes in the input array:

    <input name="options[0]" type="text">
    <input name="options[1]" type="text">
    <input name="options[2]" type="text">
    <input name="options[3]" type="text">
    

    and add the rules for each input afterwards with the selector [name^="options"], which means: each element with a name, that begins with "options":

    $('[name^="options"]').each(function() {
        $(this).rules('add', {
            required: true,
            minlength: 4,
            messages: {
              required: "Please enter at least 4 options",
              minlength: "Please enter at least 4 characters"
            }
        })
    });
    

    Working example:

    i removed the unnecessary parts (like ids, classes or spans) for simplicity...

    $("#livechatform").validate({
      submitHandler: (form) => form.submit()
    });
    
    $('[name^="options"]').each(function() {
        $(this).rules('add', {
            required: true,
            minlength: 4,
            messages: {
              required: "Please enter at least 4 options",
              minlength: "Please enter at least 4 characters"
            }
        })
    });
    .col {
      display: flex;
      flex-direction: column;
      width: 200px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js" integrity="sha512-rstIgDs0xPgmG6RX1Aba4KV5cWJbAMcvRCVmglpam9SoHZiUCyQVDdH2LPlxoHtrv17XWblE/V/PP+Tr04hbtA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    
    <form method="post" id="livechatform" action="#">
      <div class="col">
        <input name="options[0]" type="text">
        <input name="options[1]" type="text">
        <input name="options[2]" type="text">
        <input name="options[3]" type="text">
      </div>
      
      <div>
        <button type="submit">Submit</button>
      </div>
    </form>