我没有足够的声誉发表评论,但在许多情况下,公认的解决方案会抛出未捕获的异常。这是由于以下行为(从电话号码文档复制的):The parse function will also fail completely (with a NumberParseException) on inputs that cannot be uniquely parsed, or that can't possibly be phone numbers.
失败的字符串示例有“1”、“2”和“abcde”。在
以下是对wgwz的回答的修改,该回答对此类情况是可靠的:from wtforms import ValidationError
import phonenumbers
def validate_phone(message='Invalid phone number.', region=None):
""" This validates the phone number using the phonenumbers package.
Make sure to select a default region in order to validate numbers
that do not follow the international format.
"""
def _validate_phone(form, field):
try:
input_number = phonenumbers.parse(field.data, region)
if not (phonenumbers.is_valid_number(input_number)):
raise ValidationError(message)
except:
raise ValidationError(message)
return _validate_phone
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=[validate_phone(region='US'])