0

我有一个以 django 形式呈现的文本字段。此文本字段可以包含不同类型的数据,例如 ip 地址、url、常规文本等。根据表单中先前下拉菜单的输入,我如何有条件地验证文本字段?

例如,如果我在下拉列表中选择 IP 地址,那么除了在文本字段中输入 IP 地址时,我如何在输入时有条件地抛出验证错误?

4

1 回答 1

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

这一切都在这里解释:

https://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

于 2013-07-16T23:53:47.507 回答