2016-06-21 56 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