Home:ALL Converter>Formatting phone numbers for presentation and database entry using flask

Formatting phone numbers for presentation and database entry using flask

Ask Time:2018-06-08T22:05:48         Author:Tom

Json Formatter

I'm writing a flask app with wtforms backed by a Postgres db.

I want the user to enter phone numbers in pretty much any format, NNN NNN NNNN, NNNNNNNNNN, NNN-NNN-NNNN etc.

I want to store the numbers in the database without any separators NNNNNNNNNN

What is the best way to achieve this? I tried putting getters and setters on the form field but this breaks functionality when the field is unbound.

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

Author:Tom,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50762446/formatting-phone-numbers-for-presentation-and-database-entry-using-flask
yy