簡體   English   中英

停止表單提交

[英]Stop form submission

我有一個顯示帶有文本輸入和按鈕的表單的腳本。 文本輸入是必需的,但腳本僅驗證輸入是否為空/非空。

我需要更進一步,以便它僅驗證字母數字。

我無權訪問處理表單提交/驗證的文件,因為有 1000 個文件。

如果輸入字段不是字母數字,我嘗試了這個腳本來嘗試停止表單提交。 但它不起作用,無論輸入如何,表單仍然提交。 我徹底測試了validate_text_field()並且運行良好。

<script>
    jQuery(document).ready(function() {
        function validate_text_field( input_txt_val ){

            var letters = /^[0-9a-zA-Z]+$/;
            input_txt_val = $.trim( input_txt_val );
            if( input_txt_val.match(letters) ){
                    return true;
            }else{
                    return false;
            }

        }

        jQuery(".asp_product_buy_btn_container .pricing-button").click(function(e){

            var input_txt_val = $( this ).closest( '.asp_all_buttons_container' ).siblings( 'form.asp-stripe-form' ).find( ".asp_product_custom_field_input" ).val();
            var is_valid = validate_text_field( input_txt_val );
            if( is_valid ){
                alert('is valid alphanumeric');
                return true;
            }else{
                alert('is not valid alphanumeric');
                e.preventDefault()
                return false;
            }

        });
    });
</script>

如何阻止提交此表單?

preventDefault()` 當它無效時。 事件處理程序的返回值可能無法正確處理。

jQuery(document).ready(function() {
   jQuery("#stripe_button_0").click(function(e){
      var is_valid = validate_text_field();
      if( is_valid ){
         return true;
      }else{
         e.preventDefault()
         return false;
      }
   });
});

在您的 URL 中,如果您調用 validate_text_field() 我會收到一個錯誤:

ReferenceError: validate_text_field is not defined

所以首先嘗試解決這個問題。

兩個提示:您可以使用 $ 代替 'jQuery'。 另外,這個片段:

var is_valid = validate_text_field();
  if( is_valid ){
     return true;
  }else{
     return false;
  }

可以減少到

return validate_text_field();

暫無
暫無

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

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