Home > Enterprise >  JQuery on key up and on submit validation with Ajax
JQuery on key up and on submit validation with Ajax

Time:09-05

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" 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.

CodePudding user response:

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

CodePudding user response:

 $('.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  >
  <div>
    <label for="firstname">Firstname:</label><br>
    <input type="text"  name="firstname"  data-parsley-required-message="Please enter firstname" required>
  </div>
  <div>
    <label for="lastname">Lastname:</label><br>
    <input type="text"  name="lastname"  data-parsley-required-message="Please enter last name" required>
  </div>
  <input type="submit" >
</form>

  • Related