skip to Main Content

Before submitting the form, I need to first validate the data that is being input by the user on key up. Let’s say I have an input like this:

<input type="text" value="" name="title" class="input" id="title" placeholder="Job Title">

On my script I need to validate the input of the user on key up:

$("#title").on("keyup", function(e) {
    if($(this).val() == "") {
        $("#errorMsg").html('This field is required');
        return false;
    } else {
        $("#errorMsg").html('');
        return true;
    }
});

After the input has been validated successfully, the user can now submit the form, however if the input is not validated successfully and the user clicks the submit button, I need to have an error message saying "fix your errors first";

$('#save_btn').on('click', function(e){
  e.preventDefault();
  
  if ( user input is false ){
      alert('Fix your errors first!');
  } else{
      alert('Validation Successful')
  }

I will not include the ajax part of my code cause it’s already working fine. I just need this submit validation to get fixed. I’m thinking it has something to do with functions (?) but I don’t know how to execute it.

2

Answers


  1. Or you can use jquery validation plugin https://jqueryvalidation.org/documentation/

    Login or Signup to reply.
  2.  $('.demo-form').parsley();
    $(".demo-form").on("submit", function (event) {
      event.preventDefault();
      $('.demo-form').parsley().validate();
      if ($('.demo-form').parsley().isValid()) {
          //ajxt code
      }
    });
        .parsley-error {
          border-color: #ef4554 !important;
        }
        .error {
          border-color: #ef4554 !important;
          color: #f6504d;
          line-height: 1.2;
        }
        .parsley-errors-list {
          display: none;
          margin: 0;
          padding: 0;
        }
        .parsley-errors-list.filled {
          display: block;
        }
        .parsley-errors-list>li {
          font-size: 12px;
          list-style: none;
          color: #f6504d;
        }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.9.2/parsley.min.js"></script>
    You can use parsly jquery valiation
    <form class="demo-form" >
      <div>
        <label for="firstname">Firstname:</label><br>
        <input type="text" class="form-control" name="firstname"  data-parsley-required-message="Please enter firstname" required>
      </div>
      <div>
        <label for="lastname">Lastname:</label><br>
        <input type="text" class="form-control" name="lastname"  data-parsley-required-message="Please enter last name" required>
      </div>
      <input type="submit" class="btn btn-default">
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search