簡體   English   中英

在驗證之前停止提交表格

[英]Stop Form From Being Submitted Until Verified

我有一個這樣結構的表格。

<form id="email_subscription_form" class="form-inline float-right" method="post" action="/my-endpoint/">
   <div class="form-group">
      <label for="id_email_address" class="d-none">Email Address</label>
      <input type="email" id="id_email_address" class="form-control border-0 rounded-0" name="email_address" value="" placeholder="Email Address">
      <input type="hidden" name="mailpiece_slug" value="{{ page.settings.email_newsletter_slug }}" />
      <input type="hidden" name="event_slug" value="subscribe" />
   </div>
</form>

我在文件底部還有一個腳本。 該腳本的重點是在提交表單之前驗證一個recaptcha。 這是我的腳本。

<script>
    document.getElementById('email_subscription_form').addEventListener('submit', verifyRecaptcha);
    
    function verifyRecaptcha(e) {
        e.preventDefault()
        return false
    }
</script>

根據一些研究,我認為 function 返回 false 會阻止表單提交。 但是,表單仍然提交並到達端點。

我也試過這個:

<form id="email_subscription_form" class="form-inline float-right" method="post" action="/my-endpoint/" onsubmit="return verifyRecaptcha()">

<form id="email_subscription_form" class="form-inline float-right" method="post" action="/my-endpoint/" onsbubmit="return false">

但表格仍然提交。

我可以做些什么來阻止表單提交直到驗證? 這是一個 Django 項目,所以模板是 Django 模板。

我進行了一些研究,並在形式上有一個參數onsubmit="" ,您可以在其中調用驗證 function ,就像您已經使用verifyRecaptcha(e) 據我所知, return false部分應該停止表單,可能是因為您沒有在表單開始標記中使用onsubmit="verifyRecaptcha(e)" 所以直接 onload 腳本是行不通的。 您的代碼應如下所示:

html:

<form id="email_subscription_form" onsubmit="verifyRecaptcha(e) class="form-inline float-right" method="post" action="/my-endpoint/">
   <div class="form-group">
      <label for="id_email_address" class="d-none">Email Address</label>
      <input type="email" id="id_email_address" class="form-control border-0 rounded-0" name="email_address" value="" placeholder="Email Address">
      <input type="hidden" name="mailpiece_slug" value="{{ page.settings.email_newsletter_slug }}" />
      <input type="hidden" name="event_slug" value="subscribe" />
   </div>
</form>

js:

<script>
    function verifyRecaptcha(e) {
        e.preventDefault()
        return false
    }
</script>

我強烈建議您查看 django 如何幫助您使用 forms:使用 forms

django 的內置表單管理已經處理了所有好東西,例如驗證,並允許您專注於其他事情。 此外,您仍然可以像往常一樣添加您的 JS。

請參閱上面的文檔鏈接和以下示例以快速了解:

from django import forms
from django.core.exceptions import ValidationError

class ContactForm(forms.Form):
    # Everything as before.
    ...

    def clean_recipients(self):
        data = self.cleaned_data['recipients']
        if "fred@example.com" not in data:
            raise ValidationError("You have forgotten about Fred!")

        # Always return a value to use as the new cleaned data, even if
        # this method didn't change it.
        return data

這將檢查“收件人”字段中是否包含特定的 email。 如果不是,它將引發 ValidationError,聲明的文本顯示在表單中相應字段的下方。

暫無
暫無

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

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