feat(验证器): 增强 NotBlank 装饰器以支持可选字段验证 #5
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
原有的
NotBlank
装饰器会始终执行其验证逻辑,这使其不适用于那些“字段可选,但一旦提供就不能为空”的验证场景。本次提交通过引入一个新的布尔参数
allow_optional
来增强此装饰器。allow_optional
的默认值为False
,这确保了完全的向后兼容性。所有现有的装饰器用法无需任何修改即可正常工作。当
allow_optional
设置为True
时,装饰器将仅在该字段被显式提供(即存在于 Pydantic 模型的model_fields_set
中)时,才执行非空验证。此次变更极大地提高了该装饰器的通用性和灵活性,使其能覆盖更多的验证场景,并减少了为可选字段编写自定义验证逻辑或独立装饰器的需要。
可选字段使用示例:
@notblank(field_name='nickname', allow_optional=True)