简体   繁体   English

提交之前的jQuery表单验证

[英]jQuery form validation before submit

I currently have the following js that adds error class if the required fields aren't completed. 我目前有以下js,如果required字段未完成,则会添加error类。

I need an if statement if any of the require fields are empty to not post the form. 如果任何require字段为空,则我需要一条if语句以不发布表单。

Here is my JS at the moment. 这是我现在的JS。

function CheckPaymentForm(){    
    $('.required').removeClass('error').filter(function() {
        return !$.trim(this.value).length;
    }).addClass('FormError');

    var FormToSubmit = $( "#payment-form" ).serialize();    
    ProcessPayment(FormToSubmit);
};

I have tried various if statements on checking for the error class but without any joy. 我已经尝试了各种if语句来检查错误类,但没有任何喜悦。 I don't want to call the function ProcessPayment if I still have empty required fields. 如果我仍然有空的必填字段,我不想调用函数ProcessPayment

Change it to this... 改成这个...

function CheckPaymentForm(){    
    $('.required').removeClass('error').filter(function() {
        return !$.trim(this.value).length;
    }).addClass('FormError');

    // this will return before submitting, if there are any invalid inputs    
    if ($(".FormError").length) return;

    var FormToSubmit = $( "#payment-form" ).serialize();    
    ProcessPayment(FormToSubmit);
};

It simply checks for the class FormError that you add to invalid inputs. 它只是检查您添加到无效输入中的类FormError If there are any then it drops out without sumbitting. 如果有的话,它会掉下来而不累加。

Also, I think you have an error in the code. 另外,我认为您在代码中有错误。 The removeClass() should probably remove FormError instead of error . removeClass()应该删除FormError而不是error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM