我有一个以django形式呈现的文本字段。此文本字段可以包含不同类型的数据,如IP地址,网址,常规文本等。根据表单中先前的下拉输入,如何有条件地验证文本字段?
例如,如果我在下拉列表中选择ip地址,除了在文本字段中输入IP地址之外,如何在输入时有条件地抛出验证错误?
答案 0 :(得分:0)
谢谢@karthikr:
from django import forms
class ContactForm(forms.Form):
# Everything as before.
...
def clean(self):
cleaned_data = super(ContactForm, self).clean()
cc_myself = cleaned_data.get("cc_myself")
subject = cleaned_data.get("subject")
if cc_myself and subject:
# Only do something if both fields are valid so far.
if "help" not in subject:
raise forms.ValidationError("Did not send for 'help' in "
"the subject despite CC'ing yourself.")
# Always return the full collection of cleaned data.
return cleaned_data
这里都解释了: