Using pydantic to validate form data
continuous-integration/drone/push Build is failing
Details
continuous-integration/drone/push Build is failing
Details
parent
901a548d2e
commit
31ed66b1f5
@ -0,0 +1,34 @@
|
||||
import re
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
from pydantic import field_validator
|
||||
|
||||
from htmx_contact.models import PHONE_REGEX
|
||||
|
||||
EMAIL_REGEX = r'^[\w\-\.]+@([\w-]+\.)+[\w-]{2,}$'
|
||||
|
||||
|
||||
def repack_validation_errors(errors):
|
||||
repackaged_errors = {error.get('loc')[0]: error.get('msg') for error in errors}
|
||||
return repackaged_errors
|
||||
|
||||
|
||||
class NewContactValidator(BaseModel):
|
||||
first_name: str = Field(min_length=2, max_length=30)
|
||||
last_name: str = Field(min_length=2, max_length=30)
|
||||
phone: str = Field(max_length=30)
|
||||
email: str = Field(max_length=120)
|
||||
|
||||
# Field Validators used to prevent regex patterns returned in error message
|
||||
@field_validator('phone')
|
||||
def must_match_phone_pattern(value):
|
||||
if not bool(re.match(PHONE_REGEX, value)):
|
||||
raise ValueError("not a valid phone number. Please review and resubmit.")
|
||||
return value
|
||||
|
||||
@field_validator('email')
|
||||
def must_match_email_pattern(value):
|
||||
if not bool(re.match(EMAIL_REGEX, value)):
|
||||
raise ValueError("not a valid email. Please review and resubmit.")
|
||||
return value
|
@ -0,0 +1,21 @@
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from htmx_contact.validators import NewContactValidator
|
||||
from htmx_contact.validators import repack_validation_errors
|
||||
|
||||
|
||||
def test_new_contact_errors():
|
||||
with pytest.raises(ValidationError) as error:
|
||||
NewContactValidator(first_name="Drew", last_name="bednar", phone="666-7777-3333", email="not a valid email")
|
||||
assert len(error.value.errors()) == 2
|
||||
|
||||
|
||||
def test_repackage_errors():
|
||||
with pytest.raises(ValidationError) as error:
|
||||
NewContactValidator(first_name="Drew", last_name="bednar", phone="666-7777-3333", email="not a valid email")
|
||||
|
||||
repackaged_errors = repack_validation_errors(error.value.errors())
|
||||
assert len(repackaged_errors) == 2
|
||||
assert 'not a valid phone number' in repackaged_errors['phone']
|
||||
assert 'not a valid email' in repackaged_errors['email']
|
Loading…
Reference in New Issue