princesse
princesse

Reputation: 37

Is it possible to validate a form without a submit button?

I have normal buttons that I maniulate using jquery for clientside validation. The thing is I would also like to add server side validation but when the input is type submit the jquery code does not work. When I use

$('#addperson').submit(function(event){
  event.preventDefault();
  //code for client side  checks
});

The client side code does not work. Please does anybody know if there is a way to have my button work with both client side and server side?

Upvotes: 0

Views: 993

Answers (2)

yukioxD
yukioxD

Reputation: 81

'submit event' might help you

var valid = false;    
$("#valid").on('change', function(){
  valid = this.checked;
})
$('#form').on('submit', function(e){
  console.log(valid);
  if(!valid) {
    e.preventDefault();
    $('#ipt').val('oops, stopped'); 
  } else {
    $('#ipt').val('sending'); 
    //yey
  }
});

working jsbin: https://jsbin.com/nowirij/4/edit?html,console,output

Upvotes: 1

Justinas
Justinas

Reputation: 43499

Simply first do form validation client side, than do $('form').submit() and send all info to server.

$('button').click(function () {
     if (validateMyForm()) {
         $('form').submit();
     }
});

function validateMyForm() {
    // check if valid
    [...]

    return isValid
}

<form>
    <input type="text" name="name"/>
    <button type="button">Submit</button>
</form>

Upvotes: 2

Related Questions