Python 使用flask格式化演示文稿和数据库条目的电话号码

Python 使用flask格式化演示文稿和数据库条目的电话号码,python,python-3.x,flask,phone-number,wtforms,Python,Python 3.x,Flask,Phone Number,Wtforms,我正在用Postgres db支持的wtforms编写一个flask应用程序 我希望用户以几乎任何格式输入电话号码,nnnnnnnnnnnn,nnnnnnnnnnnn,NNN-NNNN等 我想在数据库中存储数字,不使用任何分隔符nnnnnnnn 实现这一目标的最佳方式是什么?我尝试将getter和setter放在表单字段上,但当字段未绑定时,这会中断功能 class myform(FlaskForm): _phone=StringField('Phone #', validators=[

我正在用Postgres db支持的wtforms编写一个flask应用程序

我希望用户以几乎任何格式输入电话号码,
nnnnnnnnnnnn
nnnnnnnnnnnn
NNN-NNNN

我想在数据库中存储数字,不使用任何分隔符
nnnnnnnn

实现这一目标的最佳方式是什么?我尝试将getter和setter放在表单字段上,但当字段未绑定时,这会中断功能

class myform(FlaskForm):
    _phone=StringField('Phone #', validators=[Regexp("\d{3}[ ,-]?\d{3}[ ,-]?\d{4}"]

    @propery
    def phone(self)
        return '{}-{}-{}'.format(self._phone[0:3],self._phone[3:6],self._phone[6:10])

   @phone.setter
   def phone(self, value):
        value = value.replace(' ','')
        value = value.replace('-','')
        self._phone = value

尽管有点不成熟,但您可以在用于验证的函数中编辑表单数据

def reformat_phone(form, field):
    field.data = field.data.replace('-', '')
    return True

class PhoneForm(FlaskForm):
    phone = StringField('Phone #', validators=[reformat_phone])
    alright = SubmitField('submit')
其他选项包括编写您自己的phone field类,以及在其中重写
process\u formdata
函数

编辑:

以下是创建自己的字段的选项:

class PhoneField(StringField):
    def process_formdata(self, valuelist):
        self.data = [v.replace('-', '') for v in valuelist]
        super().process_formdata(self.data)


class PhoneForm(FlaskForm):
    phone = PhoneField('Phone #')
    alright = SubmitField('submit')

+1用于自定义字段。谢谢你的演示如何使这项工作。我可以在presentation laywr中处理演示文稿的数字格式,这是它应该在的地方。@Joost如果
PhoneField
中的结果为False,并且它希望返回消息,是否可行?