I'm using a WTForm with a custom validator the check for properly formatted phone numbers, care of the helpful package phonenumbers (https://pypi.org/project/phonenumbers/).
During testing, Form Validation fails when an improperly formatted number is passed - this is good.
Example: (111)111-1111 -> This should fail, and does!
What isn't good is that execution stops rather than returning the ValidationError so I can display it in the form.
Simplified Example:
PhoneForm
class PhoneForm(FlaskForm):
phone_number = StringField('Phone Number', validators=[DataRequired(), Length(max=15)])
country_code = HiddenField('')
def validate_phone_and_country(self):
try:
print(f"phone no: {self.phone_number.data}")
print(f"country: {self.country_code.data}")
p = phonenumbers.parse(self.phone_number.data, self.country_code.data)
if not phonenumbers.is_valid_number(p):
raise ValueError()
except (phonenumbers.phonenumberutil.NumberParseException, ValueError):
raise ValidationError('Invalid Phone Number')
return True
Validation Code
# POST data via wtform
phone_form = PhoneForm()
error = False
if phone_form.validate_phone_and_country():
phone = PhoneRecord()
phone_form.populate_obj(phone)
db.session.add(phone)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
flash('There was a problem saving your information. Please try again.', 'danger')
error = True
else:
error = True
if error:
flash('The phone number you entered was invalid. Please try again.', 'warning')
return render_template("phone_form.html", phone)
else:
flash('Phone number successfully changed.', 'success')
return redirect(url_for('user.home'))
Expected Outcome on Bad Input:
- Validation should fail.
- Execution Continues: The view should be re-rendered with the warning and feedback in the form.
Actual Outcome on Bad Input:
- Validation Fails (good!).
- A Flask Development Debug Page appears showing the correct ValidationError (wtforms.validators.ValidationError: Invalid Phone Number). This shouldn't happen.
- Execution Stops.
Any guidance on what I'm missing here would be helpful.
Cheers!