File size: 1,449 Bytes
52c1998
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from pydantic import BaseModel, Field, field_validator
import re

UK_POSTCODE_REGEX = re.compile(r"^(GIR ?0AA|[A-Z]{1,2}\d{1,2}[A-Z]?\s?\d[A-Z]{2})$", re.IGNORECASE)

class UKAddress(BaseModel):
    street_address: str = Field(..., min_length=5, max_length=100)
    city: str = Field(..., min_length=2, max_length=50)
    postcode: str
    country: str = "United Kingdom"

    @field_validator("street_address")
    @classmethod
    def validate_street_address(cls, v: str) -> str:
        if not re.match(r"^[a-zA-Z0-9\s,.'\-/#()]{5,100}$", v):
            raise ValueError("Invalid characters in street address")
        return v.strip()

    @field_validator("city")
    @classmethod
    def validate_city(cls, v: str) -> str:
        if not re.match(r"^[a-zA-Z\s\-']+$", v):
            raise ValueError("City must only contain alphabetic characters, spaces, hyphens, or apostrophes")
        return v.strip()

    @field_validator("postcode")
    @classmethod
    def validate_postcode(cls, v: str) -> str:
        cleaned = v.replace(" ", "").upper()
        if not UK_POSTCODE_REGEX.match(cleaned):
            raise ValueError("Invalid UK postcode format")
        return v.upper()

    @field_validator("country")
    @classmethod
    def validate_country(cls, v: str) -> str:
        if v.strip().lower() not in ["united kingdom", "uk"]:
            raise ValueError("Country must be United Kingdom or UK")
        return "United Kingdom"