2017-10-11 103 views
1

我有以下jQuery以確保輸入中有正確的電子郵件地址,並且他們還檢查了要顯示的模式的複選框。下面是標記:檢查表單是否有檢查和有效的電子郵件不工作

// reveal modal if info is filled out correctly 
 
$('.hero--input_button').click(function() { 
 
    if (($('.hero--input_check').is(":checked")) && ($('.hero--input_text').val().length >= 8)) { 
 
    $('#cta-modal').addClass('modal--show'); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form id="email_signup" method="GET" target="_blank" novalidate="novalidate"> 
 
    <div class="klaviyo_field_group"> 
 
    <input type="email" value="" name="email" id="k_id_email" placeholder="Your email" class="hero--input_text" /> 
 
    <input type="checkbox" name="subscribe" value="yes" id="form--check_two" class="hero--input_check" checked /> 
 
    </div> 
 
    <div class="klaviyo_form_actions"> 
 
    <button type="submit" class="hero--input_button">Subscribe</button> 
 
    </div> 
 
</form>

如果我拿出從if語句(關於.hero - INPUT_TEXT)的最後一位的代碼工作正常。就在這時,人們可以按下按鈕並查看模式,而無需輸入電子郵件地址!

我知道我的代碼有問題,但我不知道是什麼。任何幫助或建議,不勝感激。

+1

你可以張貼HTML的例子嗎? – Niladri

+0

您的代碼正常工作正常。順便說一句,你只是檢查電子郵件的長度,你需要一個正則表達式來檢查有效的電子郵件格式。 – Niladri

+0

使用正則表達式正確驗證電子郵件地址基本上是不可能的。 (但是檢查長度是否大於8個字符也不是一個好方法。)測試一個「@」和至少一個「。」的出現並且每天調用它。 –

回答

0

您應該驗證電子郵件地址,而不是字符串長度。下面是實施e-mail validation script

// reveal modal if info is filled out correctly 
 
$('.hero--input_button').click(function(){ 
 
    if ( $('.hero--input_check').is(":checked") 
 
     && isEmail($('.hero--input_text').val())) { 
 
    $('#cta-modal').addClass('modal--show'); 
 
    console.log('here'); 
 
    } 
 
}); 
 

 
function isEmail(email) { 
 
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
 
    return regex.test(email); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form id="email_signup" method="GET" target="_blank" novalidate="novalidate"> 
 
     <div class="klaviyo_field_group"> 
 
      <input type="email" value="" name="email" id="k_id_email" placeholder="Your email" class="hero--input_text" /> 
 
      <input type="checkbox" name="subscribe" value="yes" id="form--check_two" class="hero--input_check" checked /> 
 
     </div> 
 
     <div class="klaviyo_form_actions"> 
 
      <button type="submit" class="hero--input_button">Subscribe</button> 
 
     </div> 
 
     </form>

相關問題