Search code examples
pythonflaskwtforms

Validating US phone number in WTForms


I'm working with a flask app and am using wtforms:

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

I've just added phone and am looking for a way to validate a US number. I came across http://wtforms-components.readthedocs.org/en/stable/#phonenumberfield but this does not appear to have phonenumberfield any longer. Whats the best way to handle this with wtfforms?

edited class:

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

Solution

  • I made use of python-phonenumbers in a recent application. It uses google phone number parsing stuff. Here's how I used it:

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