以驗證機器人為例:
新增一個隱藏的欄位來檢驗機器人,如屬性value有值代表是機器人,即發出資料驗證訊息。
使用clean_XXX()來驗證單一欄位
from django import forms
class FormName(forms.Form):
name = forms.CharField()
email = forms.EmailField()
text = forms.CharField(widget=forms.Textarea)
botcatcher = forms.CharField(required=False,
widget=forms.HiddenInput)
def clean_botcatcher(self):
botcatcher = self.cleaned_data['botcatcher']
if len(botcatcher) > 0:
raise forms.ValidationError("Gotcha bot!!!")
return botcatcher
另一種方法是使用validators,可以讓程式更簡短
from django import forms
from django.core import validators
class FormName(forms.Form):
name = forms.CharField()
email = forms.EmailField()
text = forms.CharField(widget=forms.Textarea)
botcatcher = forms.CharField(required=False,
widget=forms.HiddenInput,
validators = [validators.MaxLengthValidator(0)])
客製驗證,以檢驗開頭必要為z為例:
利用validators客制自己的資料驗證,新增一個method 來寫入檢驗邏輯,成立即發出error訊息。
from django import forms
from django.core import validators
def check_for_z(value):
if value[0].lower() != 'z':
raise forms.ValidationError('Name needs to start with z')
class FormName(forms.Form):
name = forms.CharField(validators=[check_for_z],)
email = forms.EmailField()
text = forms.CharField(widget=forms.Textarea)
驗證再次輸入的email與email欄位是否相符,使用clean()
使用clean()讀取多個欄位
from django import forms
from django.core import validators
class FormName(forms.Form):
name = forms.CharField(validators=[check_for_z],)
email = forms.EmailField()
verify_email = forms.EmailField(label='Enter your email again')
text = forms.CharField(widget=forms.Textarea)
def clean(self):
email = self.cleaned_data.get('email')
vmail = self.cleaned_data.get('verify_email')
if email != vmail:
raise forms.ValidationError("make sure emails match")
沒有留言:
張貼留言