2016-03-27 428 views
0

我用的燒瓶中的應用工作,並使用wtforms我:在wtfforms驗證美國電話號碼

class RegisterForm(Form): 
    username = StringField('Username', validators=[DataRequired(), Length(min=3, max=25)]) 
    email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)]) 
    phone = StringField('Phone', validators=[DataRequired(), Length(10)]) 

我剛加入手機和正在尋找一種方法來驗證一個美國號碼。我遇到了http://wtforms-components.readthedocs.org/en/stable/#phonenumberfield,但這似乎不再有phonenumberfield。什麼是最好的方式來處理這與wtfforms?

編輯類:

class RegisterForm(Form): 
    username = StringField('Username', validators=[DataRequired(), Length(min=3, max=25)]) 
    email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)]) 
    phone = StringField('Phone', validators=[DataRequired(),validate_phone('RegisterForm','phone'), Length(min=6, max=40)]) 

    def validate_phone(form, field): 
     if len(field.data) > 16: 
      raise ValidationError('Invalid phone number.') 
     try: 
      input_number = phonenumbers.parse(field.data) 
      if not (phonenumbers.is_valid_number(input_number)): 
       raise ValidationError('Invalid phone number.') 
     except: 
      input_number = phonenumbers.parse("+1"+field.data) 
      if not (phonenumbers.is_valid_number(input_number)): 
       raise ValidationError('Invalid phone number.') 
+0

您可以使用正則表達式驗證程序作爲驗證程序中的附加參數。很久以前,因爲我使用它,只是嘗試它。希望能幫助到你。 Regexp(''^ \ w + $'',message =「輸入有效的美國電話號碼」), – Roman

+0

[根據更新日誌](https://github.com/kvesteri/wtforms-components/blob/35bdf49681eec08c1d4462954133bb45cb9644de/CHANGES 。#第一個#0100-2016-01-28),'PhoneNumber' [移動到WTForms-Alchemy](https://github.com/kvesteri/wtforms-components/blob/35bdf49681eec08c1d4462954133bb45cb9644de/CHANGES.rst#0100-2016- 01-28)。 – dirn

回答

4

我在最近的應用程序利用了python-phonenumbers。它使用谷歌手機號碼解析的東西。以下是我如何使用它:

from wtforms import ValidationError 
import phonenumbers 

class RegisterForm(Form): 
    username = StringField('Username', validators=[DataRequired(), Length(min=3, max=25)]) 
    email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)]) 
    phone = StringField('Phone', validators=[DataRequired()]) 

    def validate_phone(form, field): 
     if len(field.data) > 16: 
      raise ValidationError('Invalid phone number.') 
     try: 
      input_number = phonenumbers.parse(field.data) 
      if not (phonenumbers.is_valid_number(input_number)): 
       raise ValidationError('Invalid phone number.') 
     except: 
      input_number = phonenumbers.parse("+1"+field.data) 
      if not (phonenumbers.is_valid_number(input_number)): 
       raise ValidationError('Invalid phone number.') 
+0

我把手機輸入作爲'StringField'以及 – wgwz

+0

謝謝,你如何將validate_phone附加到手機領域?我嘗試:手機=字符串字段('電話',驗證= [DataRequired(),validate_phone(RegisterForm,電話),長度(最小= 6,最大= 40)]))有點未解決功能錯誤 – user61629

+0

你只需要添加validate_fieldname方法給你的班級。請參閱:http://wtforms.simplecodes.com/docs/0.6.1/validators.html#custom-validators – wgwz