You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
On Pydantic 2.8.2 with Pydantic-core 2.20.0 I've noticed some inconsistent behavior validating strings using a pattern where passing the pattern as a string allows invalid inputs to pass validation, while passing the pattern as a compiled Pattern object from re.compile exhibits the expected behavior and rejects the invalid input.
Example:
importrefrompydanticimportBaseModel, Field# Note: this regular expression is based on the lowercase RFC1123 subdomain name regular expression# the Kubernetes project uses to validate the names of Secrets and other resources.COMPILED=re.compile(r"[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*")
NOT_COMPILED=r"[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*"classNotCompiled(BaseModel):
name: str=Field(pattern=NOT_COMPILED)
classCompiled(BaseModel):
name: str=Field(pattern=COMPILED)
model=NotCompiled.model_validate({"name": "ShouldntPass"})
print(repr(model))
# NotCompiled(name='ShouldntPass')model=Compiled.model_validate({"name": "ShouldntPass"})
print(repr(model)) # unreachable, previous line raises ValidationError as expected
The validation process for b will succeed, but it will fail for c. This seems to happen because in the first case, pydantic_core chooses to use rusts's regex as the regex engine and in the second case it simply calls pythonic re.Pattern.match method. The rust Regex.is_match implementation however, behaves more like python's re.search, in the docs we can find (emphasis mine):
Returns true if and only if there is a match for the regex anywhere in the haystack given.
Issue Description
On Pydantic 2.8.2 with Pydantic-core 2.20.0 I've noticed some inconsistent behavior validating strings using a pattern where passing the pattern as a string allows invalid inputs to pass validation, while passing the pattern as a compiled
Pattern
object fromre.compile
exhibits the expected behavior and rejects the invalid input.Example:
This can be reproduced by adding the following two test cases to tests/validators/test_string.py:
Environment Info
Here is some information on the environment where I noticed the issue:
The text was updated successfully, but these errors were encountered: