Home > Software design >  Validate form by jquery before submitting
Validate form by jquery before submitting

Time:09-22

In form I have 2 buttons:

<button type="submit">Submit</button>
<button type="submit" name="rdraft" value="1">Save to drafts</button>

First is actually publishes content, second one just saves it to draft. And on form submit I validate form fields with Jquery:

$('#form').submit(function(e) {
//validation scripts
});

How can I validate my form only when first button clicked and skip validation if it is a draft?

CodePudding user response:

You can use onClick event for submit button

function validate(e){
  var formData = new FormData(document.forms.myForm);
  const jsonFormData = Object.fromEntries(formData);
  if(!jsonFormData['name']){
    event.preventDefault();
    alert("Please enter name");
  }
}
<form name="myForm">
<input type="text" name="name" />
<button type="submit" onclick="return validate();">Submit</button>
<button type="submit" name="rdraft" value="1">Save to drafts</button>
</form>

CodePudding user response:

Another solution would be using submitter

$('#form').submit(function(e) {
  const submitterValue = e.originalEvent.submitter.value;
  if(submitterValue!=1){
     // do validation
     e.preventDefault();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="form">
  <input type="text" name="name" />
  <button type="submit">Submit</button>
  <button type="submit" name="rdraft" value="1">Save to drafts</button>
</form>

  • Related