How to not submit a form if validation is false

2019-06-22 14:54发布

How can I make sure the form won't submit if one of the validations is false?

$('#form').submit(function(){
    validateForm1();
    validateForm(document.forms['dpart2']);
    validateForm(document.forms['dpart3']);                     
}); 

5条回答
叛逆
2楼-- · 2019-06-22 14:57
$('#form').submit(function(){
    return (validateForm1() &&
            validateForm(document.forms['dpart2']) &&
            validateForm(document.forms['dpart3']))
});

Basically, you return false in the event handler function.

查看更多
孤傲高冷的网名
3楼-- · 2019-06-22 15:07

Okay, some of the other solutions will have a lazy fail... you probably want all your validation to run, so that all errors are displayed. The presumption is that your validation methods will return false if they fail.

$("#myform").submit(function() {

    var ret = true;
    ret = validateForm1() && ret;
    ret = validateForm(document.forms['dpart2']) && ret
    ret = validateForm(document.forms['dpart3'])) && ret
    return ret;

});

This way all your validators will be called, but the Boolean value for any failure, will result in a fail.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-06-22 15:07

A thought that comes up automatically: Even if you implemented thorough client side validation be prepared to receive any invalid request data on the server that you can possibly imagine.

Client-side validation never keeps you from server-side validation. It is just a bonus in usability.

查看更多
forever°为你锁心
5楼-- · 2019-06-22 15:10

If validateForm(...) and validateForm1() return a boolean (true means that no validation error occurred), then you try to do that :

$('#form').submit(function(){
    if (!validateForm1() || !validateForm(document.forms['dpart2']) || !validateForm(document.forms['dpart3'])) {
        return false;
    }
});
查看更多
成全新的幸福
6楼-- · 2019-06-22 15:17

If the function returns false, form won't be submitted.

$('#form').submit(function(){
    return  validateForm1() 
            && validateForm(document.forms['dpart2']) 
            && validateForm(document.forms['dpart3']);                                         
              }
});
查看更多
登录 后发表回答