簡體   English   中英

jQuery提交驗證不起作用

[英]jquery submit validation not working

js

 function checkgender(){
       $("#gender-result").hide();
          if (undefined == $("input[name='gender']:checked", "#contact-form").val()) {
               $("#gender-result").html('gender requirements.').show();
               $("#gender-result").css('color', 'red');
               return false;          
          }else{
                $("#gender-result").hide();
          }
          return true;
     }

function checkpassword(){
        var password_value = $("#reg-password").val();

        if(password_value === ""){
            //password emtpy
            $("#password-result").html('Please make a password');
            $("#password-result").css('color', 'red');
            $('#reg-password').css('border-color', 'red');
        }else if (password_value.length < 6){
            //password is too shot 6 digi
            $("#password-result").html('Your password is too short.');
            $("#password-result").css('color', 'red');
            $('#reg-password').css('border-color', 'red');
        }else{
            //password passed
            $("#password-result").html('');
            $('#reg-password').css('border-color', '#dfe0e6');
            return true;
        }
        return false;
    }

但是,如果我使用它來提交驗證,為什么它不起作用

   $(document).click(function() {
            $('#contact-form').submit(function(){
                event.preventDefault();
                //validation
                if(!checkgender() && !checkpassword()){
                return false;
                }else{
                return true;
                }
                });
            });

如果我提交其中一個功能正常工作,但是如果我將2放在一起然后按Submit,即使其中一個為空,它也讓我通過了驗證,為什么? 我在這里做錯了什么?

如果其中任何一個條件失敗,則需要返回false

$(document).click(function () {
    $('#contact-form').submit(function () {
        //validation
        if (!checkgender() || !checkpassword()) {
            return false;
        } else {
            return true;
        }
    });
});

要么

短一點

$(document).click(function () {
    $('#contact-form').submit(function () {
        //validation
        return checkgender() && checkpassword();
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM