我想在屏幕上显示错误信息,如果用户输入无效的电子邮件id或电子邮件id存在于文本文件“输入您的电子邮件”使用表单验证错误信息。 目前我写了下面的一段代码显示形式验证错误信息。 但此错误消息总是显示在“新密码”测试字段旁边。 如果用户输入了无效的电子邮件id或现有的电子邮件id,我可以在“电子邮件”旁边显示表单验证错误信息吗?
HTML代码:
null
<fieldset class="module aligned wide">
{% csrf_token %}
<div class="form-row">
{{ form.old_password.errors }}
<label for="{{ form.id_old_password.id_for_label }}">Old password:</label> {{ form.old_password }}
</div>
<div class="form-row">
{{ form.new_password1.errors }}
<label for="{{ form.id_new_password1.id_for_label }}">New password:</label> {{ form.new_password1 }}
</div>
<div class="form-row">
{{ form.new_password2.errors }}
<label for="{{ form.id_new_password2.id_for_label }}">Password (again):</label> {{ form.new_password2 }}
</div>
<div class="form-row">
{{ form.email_reset.errors }}
<label for="{{ form.email_reset.id_for_label }}">Enter Your Email (optional):</label> <input id="id_email_reset" placeholder="Enter your email" name="email_reset" type="email" pattern=".+@.+\.com"/>
</div>
</fieldset>
null
Forms.py
null
class CustomPasswordChangeForm(PasswordChangeForm):
""" This is a customized class to validate the password by overriding
the existing function "clean_new_password1" from base class PasswordChangeForm.
"""
MIN_LENGTH = 8
MAX_LENGTH = 64
field_order = ['oldpassword', 'password1', 'password2']
def clean_new_password1(self):
password1 = self.cleaned_data.get('new_password1')
# At least MIN_LENGTH long
if len(password1) < self.MIN_LENGTH:
raise forms.ValidationError("The new password must be atleast %d characters long." % self.MIN_LENGTH)
# At most MAX_LENGTH long
if len(password1) > self.MAX_LENGTH:
raise forms.ValidationError("The new password must be maximum %d characters long." % self.MAX_LENGTH)
#if email id is given, then update it in database.
if len(self.data['email_reset'].strip()) > 0:
self.user.email = self.data['email_reset']
if (User.objects.filter(email=self.user.email).count() > 1):
raise forms.ValidationError("This email Id is already exist for different account. Please use different email id.")
return password1
null
首先,为什么在clean_password_new方法中有电子邮件验证? 这就是为什么您的所有错误都显示在password_new
字段中,请在clean
或clean_email_reset
中执行。如果您在clean()
中执行,您可以使用self.add_error(“email_reset”,“错误消息”)
,或者根据电子邮件验证将所有代码复制到clean_email_reset
方法中
<div class="form-row">
{{form.old_password.label_tag}}
{{form.old_password}}
{% if form.old_password.errors %}
{% for error in form.old_password.errors %}
<div class="alert alert-danger validation">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
</div>
CSS
.validation{
position: absolute;
z-index: 1000;
padding: 10px;
}