Skip to content

Instantly share code, notes, and snippets.

@cthoyt
Created June 22, 2024 09:39
Show Gist options
  • Save cthoyt/89ea8eb7cc008efbcc89a944c43af215 to your computer and use it in GitHub Desktop.
Save cthoyt/89ea8eb7cc008efbcc89a944c43af215 to your computer and use it in GitHub Desktop.
Use the Bioregistry for Pydantic (v2) validation
import bioregistry
from pydantic.functional_validators import AfterValidator
def validate_local_identifier(prefix: str) -> AfterValidator:
"""Make a validator function based on a Bioregistry prefix.
Example usage:
.. code-block:: python
from typing import Annotated
from pydantic import BaseModel
class Scholar(BaseModel):
orcid: Annotated[str, validate_local_identifier("orcid")]
Scholar(orcid="0000-0003-4423-4370") # works
Scholar(orcid="nope") # fails to pass regular expression check
"""
resource = bioregistry.get_resource(prefix)
if not resource:
raise ValueError
def _validate(identifier: str) -> str:
if not resource.is_valid_identifier(identifier):
raise ValueError
return identifier
return AfterValidator(_validate)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment