验证空格,空格和整数

时间:2013-05-23 05:05:31

标签: django django-models django-forms django-views

如何在单个方法中验证空格,空格和整数。考虑我的forms.py

class UserprofileForm(forms.ModelForm):
    class Meta:
        model = Userprofile
        fields=['username1','phonenumber1','username1','phonenumber1']

如何验证这一点。

  • 所有字段都不是必填字段。
  • 但如果输入了username1或username2且未分别输入phonenumber1或phonenumber2,则会引发验证错误。
  • 如果输入任何空格,则还应引发验证错误。
  • 是否可以在views.py中使用strip()来验证空格。

任何人都可以告诉我们如何实现这一目标。请举例说明如何执行。

谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用clean()方法在其中执行验证逻辑:

class UserprofileForm(forms.ModelForm):
    class Meta:
        model = Userprofile
        fields=['username1','phonenumber1','username1','phonenumber1']

    def clean(self):
        # do your validation here, such as
        cleaned_data = super(UserprofileForm, self).clean()
        username1 = cleaned_data.get("username1")
        username2 = cleaned_data.get("username2")
        phonenumber1 = cleaned_data.get("phonenumber1")
        phonenumber2 = cleaned_data.get("phonenumber2")
        if (
            ((username1 and not username1.isspace()) and not phonenumber1) or
            ((username2 and not username2.isspace()) and not phonenumber2) or
            ((not username1 or username1.isspace()) and phonenumber1 is not None) or
            ((not username2 or username2.isspace()) and phonenumber2 is not None)
        ):
            raise forms.ValidationError("Name and phone number required.")
        return cleaned_data

您可以参考Django Doc:

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

答案 1 :(得分:0)

class UserprofileForm(forms.ModelForm):
    class Meta:
        model = Userprofile
        fields=['username1','phonenumber1','username2','phonenumber2']

    def clean(self):
        if 'username1' in self.cleaned_data and 'phonenumber1' in self.cleaned_data:
            if not (self.cleaned_data['username1'] and self.cleaned_data['phonenumber1']):
                raise forms.ValidationError("You must enter both username1 and phonenumber1")
        if 'username2' in self.cleaned_data and 'phonenumber2' in self.cleaned_data:
            if not (self.cleaned_data['username2'] and self.cleaned_data['phonenumber2']):
                raise forms.ValidationError("You must enter both username2 and phonenumber2")


        return self.cleaned_data

您可以查看此验证方法。 thnaks