37

By the use of the jQuery plugin Validation, I am trying to, well, validate my form. When the validation passes, I want a javascript to fire with values from the form and then stop. no actual form submission with browsing to a new/same site.

is this possible with jquery validation?

alex
  • 1,277
  • 3
  • 14
  • 30

4 Answers4

60

You may try this (Example):

$(function(){
    $("#myform").validate();    
    $("#myform").on('submit', function(e) {
        var isvalid = $("#myform").valid();
        if (isvalid) {
            e.preventDefault();
            alert(getvalues("myform"));
        }
    });
});

function getvalues(f)
{
    var form=$("#"+f);
    var str='';
    $("input:not('input:submit')", form).each(function(i){
        str+='\n'+$(this).prop('name')+': '+$(this).val();
    });
    return str;
}
The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • 2
    Came to the page with a similar issue. ` var isvalidate=$("#myform").valid();` was exactly what I was looking for. Thanks +1 – Adam Tomat Nov 16 '12 at 10:05
  • Weird, in my case, `valid()` is returning false but I cannot stop the form submit with `return false` or `e.preventDefault()` or even both! – JacobIRR Oct 11 '17 at 22:31
14
$("#form").validate({
  rules: {...},
  submitHandler: function(form, event) { 
    event.preventDefault();
    alert("Do some stuff...");
    //submit via ajax
  }
});
que1326
  • 2,227
  • 4
  • 41
  • 58
  • 1
    `submitHandler` is fired when an invalid form is submitted. You might want to include `invalidHandler` to prevent form submission when it isn't valid. – Supreme Dolphin Aug 21 '18 at 10:53
12

Yes:

$("form").submit(function(event) {
    if (somethingIsInvalid) { 
      event.preventDefault();
    }
});
Ram
  • 143,282
  • 16
  • 168
  • 197
6

There's a method called .valid() which return true in case the there's no errors in you form, so you can validate first with this and then send the form here's the documentation

http://docs.jquery.com/Plugins/Validation/valid

Jorge
  • 17,896
  • 19
  • 80
  • 126