Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 38 ยท Validation and Constraints

Validating Special Types: Email, URL, Secrets

Use Pydantic's built-in special types: EmailStr, HttpUrl, AnyUrl, SecretStr, IP addresses, PastDate, AwareDatetime, ByteSize and Json, with the pitfalls of each.

Many values have well-known rules: an email has an @, a URL has a scheme and host, a password must not leak into logs. Writing regular expressions for these is error-prone, so Pydantic ships ready-made types. In this lesson you will use the most important ones.

EmailStr

EmailStr validates email addresses with the email-validator package, which is a separate install (pip install "pydantic[email]"). It checks the syntax, normalizes the domain to lowercase, and returns a string.

Python Email addresses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

On the site the package has to be installed with micropip; on your machine, install it once with pip. EmailStr checks the form of an address, not whether the mailbox exists. The only real test of an address is to send a message to it.

URLs: HttpUrl and AnyUrl

HttpUrl accepts only http and https. AnyUrl accepts any scheme. The result is a URL object with parts you can read, not a plain string.

Python URL types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Use str(url) when you need a plain string, for example to pass the URL to another library. Specialized types such as PostgresDsn, RedisDsn, MongoDsn and AmqpDsn check connection strings for the matching scheme; they are common in settings classes.

SecretStr and SecretBytes

Passwords and API keys must not appear in logs or in print output. SecretStr hides its value in repr, str, and JSON dumps; you read the real value only on purpose, with get_secret_value().

Python Keeping secrets out of output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

SecretStr is a guard against accidents, not encryption. The value lives in memory as plain text. It also does not replace hashing: never store passwords, store a hash.

Dates with rules

Type Rule
PastDate, FutureDate the date must be before or after today
PastDatetime, FutureDatetime the same for datetimes
AwareDatetime must include a timezone offset
NaiveDatetime must NOT include an offset
Python Dates with rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The examples use far-future dates so the output never changes, but the checks are made against today's date every time.

IP addresses, sizes and JSON strings

Python IP, ByteSize and Json

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

  • IPvAnyAddress accepts IPv4 or IPv6. For one version use IPv4Address or IPv6Address.
  • ByteSize understands strings like "5MiB", "2 GB" and plain integers.
  • Json[T] takes a string containing JSON, parses it, and validates the result as T. It is useful for form fields or database columns that store JSON text.

Other types worth knowing

  • FilePath and DirectoryPath: the path must exist on disk and be a file or a directory.
  • UUID1, UUID3, UUID4, UUID5: a UUID of a specific version.
  • Base64Bytes and Base64Str: decode Base64 input.
  • PaymentCardNumber: checks digits and the Luhn checksum (a format check only).
  • NameEmail: parses "Ada Lovelace <[email protected]>" into name and address.
  • ImportString: imports an object from a dotted path such as "math.sqrt"; never use it on untrusted input.

Contact and web

EmailStr Needs email-validator
HttpUrl A URL object
PostgresDsn Connection strings
1 / 3

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does EmailStr verify?

    EmailStr checks syntax (and normalizes the domain). Only sending an email can prove that an address works.
  2. 2. How do you read the real value of a SecretStr?

    The value is hidden everywhere unless you call get_secret_value() on purpose.
  3. 3. What is the difference between HttpUrl and AnyUrl?

    Use HttpUrl for web links and AnyUrl (or a Dsn type) for other schemes such as postgres://.
  4. 4. What does Json[list[int]] expect as input?

    Json[T] parses a JSON string and validates the result as T.

Summary

  • EmailStr needs the email-validator package and checks the form of an address only.
  • HttpUrl/AnyUrl return URL objects with scheme, host, port, path, query; *Dsn types check connection strings.
  • SecretStr/SecretBytes hide values in output; they are not encryption.
  • PastDate, FutureDate, AwareDatetime, NaiveDatetime add date rules; IPvAnyAddress, ByteSize and Json[T] parse common formats.
  • Prefer these types over regular expressions.

Next: Dumping to Dicts and JSON