django中的整数验证不起作用

时间:2013-05-14 14:33:09

标签: django django-forms django-templates

forms.py

class UserCreateProfileForm(forms.ModelForm):
    fields = ['phone_daytime', 'phone_mobile']

    def clean(self):
        cd=self.cleaned_data
        validate_integer(cd.get('phone_daytime', None))
        validate_integer(cd.get('phone_mobile', None))
        return cd

     def validate_integer(phone_daytime,phone_mobile):
    try:
        int(phone_daytime,phone_mobile)
    except (ValueError, TypeError):
        raise ValidationError('Phone number must be number')

我想用两个电话号码字段验证表单。

上述不起作用,不会抛出任何错误但不起作用。

该字段不应接受字母,特殊字符和空白也允许。如何进行此验证。

由于

2 个答案:

答案 0 :(得分:0)

编辑:是的,我绝对会使用它。 https://docs.djangoproject.com/en/1.5/ref/contrib/localflavor/手机领域已经在很多国家实施,肯定也是你的。

印度:

  

验证数据是否为有效的印度电话号码,包括   STD代码。它被标准化为0XXX-XXXXXXX或0XXX XXXXXXX格式。该   第一个字符串是STD代码,它是一个'0'后跟2-4个数字。   如果STD代码是3位数,则第二个字符串是8位,如果是,则是7位数   如果STD代码是5位,则STD代码是4位数和6位数。该   第二个字符串将以1到6之间的数字开头。分隔符   是一个空格或连字符。

import re

phone_digits_re = re.compile(r"""
(
(?P<std_code> # the std-code group
^0 # all std-codes start with 0
(
(?P<twodigit>\d{2}) | # either two, three or four digits
(?P<threedigit>\d{3}) | # following the 0
(?P<fourdigit>\d{4})
)
)
[-\s] # space or -
(?P<phone_no> # the phone number group
[1-6] # first digit of phone number
(
(?(twodigit)\d{7}) | # 7 more phone digits for 3 digit stdcode
(?(threedigit)\d{6}) | # 6 more phone digits for 4 digit stdcode
(?(fourdigit)\d{5}) # 5 more phone digits for 5 digit stdcode
)
)
)$""", re.VERBOSE)

取自here

在你的模特中:

from django.core.validators import RegexValidator

class YourProfileModel(Model):
    phone_field = CharField(max_lenght=12, validators=[RegexValidator(regex=phone_digits_re)])

答案 1 :(得分:0)

对于电话号码的验证,这是您应采取的方法。

class UserCreateProfileForm(forms.ModelForm):
    fields = ['phone_daytime', 'phone_mobile']

    def clean(self):
        cd = self.cleaned_data
        validate_phonenumber(cd.get('phone_daytime', None))
        validate_phonenumber(cd.get('phone_mobile', None))
        return cd

    def validate_phonenumber(phone_number):
        for char in phone_number:
            if not char.isdigit():
                raise ValidationError("Phone number must be number")

您的代码中出现的错误是您尝试int(phone_daytime, phone_mobile)。 这是不正确的,这会引发TypeError()。 您所做的也会从电话号码中删除前导0。现在这并不是那么糟糕,因为你没有使用解析后的数字,但很高兴知道。