2016-06-21 52 views
-1

您好我无法找到一个验证,一个charfield必须与另一个charfieldCharfield必须与另一个Charfield Django的表单验证匹配

比如我想这NEW_PASSWORD必须confirm_new_password匹配验证匹配的文档:

class ChangePassword(forms.Form): 
    new_password = forms.CharField(label='New Password', max_length=100, error_messages={'required': 'New password is required'}, widget=forms.PasswordInput()) 
    confirm_new_password = forms.CharField(label='Confirm New Password', max_length=100, error_messages={'required': 'Confirm New password is required'}, widget=forms.PasswordInput()) 

https://docs.djangoproject.com/en/1.9/ref/forms/fields/#charfield

看来主要的有required, max_length, min_length

+1

[清洁和互相依赖的验证领域(https://docs.djangoproject.com /en/1.9/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other) – Sayse

+0

它是表单验证下的第一个标题之一。 – Sayse

+0

请注意,Django带有内置身份验证[视图](https://docs.djangoproject.com/en/1.9/topics/auth/default/#built-in-auth-views)和[窗体](https:/ /docs.djangoproject.com/en/1.9/topics/auth/default/#built-in-auth-forms)来处理更改密码。使用这些而不是写你自己的。 – Alasdair

回答

-1

执行自定义表单验证,你需要重写洁()函数,就像这样:

class ChangePassword(forms.Form): 
    new_password = forms.CharField(label='New Password', max_length=100, error_messages={'required': 'New password is required'}, widget=forms.PasswordInput()) 
    confirm_new_password = forms.CharField(label='Confirm New Password', max_length=100, error_messages={'required': 'Confirm New password is required'}, widget=forms.PasswordInput()) 

    def clean(self): 
     password = self.cleaned_data['new_password'] 
     confirm_password = self.cleaned_data['confirm_new_password'] 
     if password != confirm_password: 
      raise forms.ValidationError('Your passwords do not match!') 
+0

如果用户没有为其中一个字段输入值,则此示例将给出一个“KeyError”。 Sayse链接的文档显示如何正确执行此操作。 – Alasdair

+0

正确,谢谢你的回应。这只是为了解决突出显示的主要问题。 – zubhav