使用Django Forms定义表单时,如果我有一个EmailField,我会得到一些像我在图片中显示的那样整洁的弹出窗口:
但如果我引入自定义验证,我无法以相同的方式向用户显示错误(使用弹出窗口)
这是我的forms.py:
from django import forms
from launcher.models import InterestedUser
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
class JoinForm(forms.ModelForm):
# this is the only field that is actually filled by the user
email = forms.EmailField(max_length=128, help_text="Introduce la cuenta de gmail que tienes asociada a tu"
"dispositivo Android",
widget=forms.EmailInput(attrs={'class': "w-input email_input",
'placeholder': 'Tu email de Google'}),
required=True, validators=[RegexValidator(regex='^([a-zA-Z0-9_\.\-])+\@(gmail.com)+$',
message="La dirección de email no es válida",
code="invalid_gmail_address")])
print("atributos {0}".format(email.widget.attrs['class']))
# this other fields will have the same value and go hidden in the form
name = forms.CharField(widget=forms.HiddenInput(), initial="(not specified)")
subject = forms.CharField(widget=forms.HiddenInput(), initial="(no subject)")
via = forms.CharField(widget=forms.HiddenInput(), initial="Join")
content = forms.CharField(widget=forms.HiddenInput(), initial="no content")
def clean_email(self):
email = self.cleaned_data.get('email')
try:
beta_tester = InterestedUser.objects.get(email=email)
# Si el email no existiese entonces salimos del clean_email y devolvemos el valor (aunque no se haya modificado)
except InterestedUser.DoesNotExist:
return email
# Si el email ya existía sacamos un error de Validación:
raise forms.ValidationError("Ya estabas anotado como Beta Tester, introduce un email diferente!")
class Meta:
model = InterestedUser
fields = ('email', 'name', 'subject', 'via', 'content',)
这就是我在模板中呈现它的方式:
<div class="w-form formulario" id="formulario">
<form class="w-clearfix formulario_subscribe" name="email-form" id="join_form" method="post" data-name="Email Form" action="/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input class="w-button email_submit_button" type="submit" id="btn_send" value="Join" data-wait="Un momento!..."/>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
</form>
</div>
我有一个RegexValidator,如果用户输入没有以默认验证器执行的相同方式(弹出窗口)传递验证器,我想显示错误消息!任何想法??
提前多多感谢。
答案 0 :(得分:1)
我认为此弹出窗口是由浏览器验证HTML5电子邮件字段(看起来像chrome)创建的,您可以禁用此验证,将novalidate
属性添加到表单字段。或者更有趣的是,您可以使用pattern
来检查gmail.com地址,例如:
<input type="email" pattern="/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@gmail.com$" />
如果您想在客户端进行验证,可以使用parsley
之类的内容此外,您还可以检查EmailValidator,而不是使用正则表达式验证电子邮件。您可以使用属性domain_whitelist
来限制gmail.com域名。