验证 passwordpassconf 两个字段提交的值相等,即用户注册时确认密码的验证。

代码如下,表单验证方法在 clean() 函数部分,首先使用 super() 取得父类的表单数据,并对其做“清洁”处理,然后声明需要对比的值,最后通过条件语句进行判断,如果两个值不一致就引发错误并给出错误消息。

forms.py

from django import forms

class UserRegistryForm(forms.Form):
    username = forms.CharField(label='用户名', max_length=50)
    email = forms.EmailField(label='E-mail', max_length=100)
    password = forms.CharField(
        label='密码', 
        widget=forms.PasswordInput,
        min_length=6,
        error_messages={'min_length': '密码最少 6 位'}
        )
    passconf = forms.CharField(label='确认密码', widget=forms.PasswordInput)

    def clean(self):
        cleand_data = super(UserRegistryForm, self).clean()
        password = cleand_data.get('password')
        passconf = cleand_data.get('passconf')

        if password != passconf:
            raise forms.ValidationError(
                '两次输入的密码不一致,请重新输入!'
            )