2013-05-14 63 views
1

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') 

我想驗證有兩個電話號碼字段的形式。

上述不工作,沒有拋出任何錯誤,但沒有運作。

該字段不應該接受字母,特殊字符和空白也允許。如何做這個驗證。

謝謝

+0

你的'validate_integer()'是如何實現的? – 2013-05-14 14:35:59

+0

validate_integer是一個內置函數嗎? – bozdoz 2013-05-14 14:36:40

+0

'-'呢?這可不是在電話號碼? – bozdoz 2013-05-14 14:41:15

回答

0

編輯:是的,我會definetly使用此。 https://docs.djangoproject.com/en/1.5/ref/contrib/localflavor/電話字段已經在很多國家實施,當然也是你的。

對於印度:

驗證數據是有效的印度的電話號碼,包括 STD代碼。它被標準化爲0XXX-XXXXXXX或0XXX XXXXXXX格式。 第一個字符串是STD代碼,它是一個「0」,後跟2-4個數字。 如果STD代碼是3位數字,則第二個字符串是8位;如果 STD代碼是4位數字,則第二個字符串是7位數字;如果STD代碼是5位數字,則第二個字符串是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

中更新,但他們不想添加驗證器。 – karthikr 2013-05-14 14:37:06

+0

@karthikr這是文檔示例,仍在編輯我的答案。 thx – 2013-05-14 14:39:40

+0

我明白了。但是沒有內置的validate_integer驗證器。你將不得不實施它。猜測已經完成 - 這是OP沒有得到任何錯誤 – karthikr 2013-05-14 14:40:17

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。既然你沒有使用分析過的號碼,但是很高興知道,現在這並沒有那麼糟糕。

+0

我的運氣不好,它不工作,我不知道什麼地方出了問題 – 2013-05-14 15:29:11

+0

'不工作'是什麼意思? – 2013-05-14 15:31:23

+0

它沒有拋出任何錯誤,驗證沒有發生 – 2013-05-14 15:32:58