Python WTForms RegEx Phone Number Validation Not Working

Viewed 649

I'm creating a form using WTForms that should take a phone number input in the format "xxx-xxx-xxxx" and for some reason, it is not doing its job.

phone = StringField(
    'phone',
    validators=[
        Regexp(
            regex=r"^\d{3}[-]{1}\d{3}[-]{1}\d{4}$",
            message="Valid phone number format is xxx-xxx-xxxx"
        )
    ]
)

I tried being more descriptive with my RegEx and I even tried writing a custom validator and it also didn't work.

import re
from wtforms.validators import ValidationError

def validatePhoneNum(form, field):
    if not re.search(r"\d{3}[-]\d{3}[-]\d{4}$", field.data):
        raise ValidationError("Invalid phone number")

phone = StringField(
    'phone',
    validators=[validatePhoneNum]
)
1 Answers

Had a similar problem. Your first solution was enough. YOu only needed to import Regexp from the form

from wtforms.validators import DataRequired, AnyOf, URL, Regexp
Related