jquery validation: prevent form submit

社会主义新天地 提交于 2020-01-19 00:42:08

问题


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?


回答1:


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;
}



回答2:


Yes:

$("form").submit(function(event) {
    if (somethingIsInvalid) { 
      event.preventDefault();
    }
});



回答3:


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




回答4:


$("#form").validate({
  rules: {...},
  submitHandler: function(form, event) { 
    event.preventDefault();
    alert("Do some stuff...");
    //submit via ajax
  }
});


来源:https://stackoverflow.com/questions/10305938/jquery-validation-prevent-form-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!