英文:
How to validate if a string field is all uppercase without custom validators
问题
在pydantic中,有没有一种方法可以验证字符串字段中的所有字母是否都是大写,而无需使用自定义验证器?
使用以下代码可以将输入字符串转换为全大写字符串。但我想要验证输入,以便不允许包含小写字母的字符串。
from pydantic import BaseModel, constr
class FooSchema(BaseModel):
foo: constr(to_upper=True)
和
foo_obj = FooSchema.parse_raw({"foo": "abc"})
print(foo_obj.foo) # 结果: "ABC"
有什么想法吗?
英文:
In pydantic, is there a way to validate if all letters in a string field are uppercase without a custom validator?
With the following I can turn input string into an all-uppercase string. But what I want is to validate the input so that no string with lower letters is allowed.
from pydantic import BaseModel, constr
class FooSchema(BaseModel):
foo: constr(to_upper=True)
and
foo_obj = FooSchema.parse_raw({foo:"abc"})
print(foo_obj.foo) # result: "ABC"
Any idea?
答案1
得分: 1
您可以使用regex
(^[^a-z]*$
)参数来验证字符串是否全为大写。
from pydantic import BaseModel, constr
class FooSchema(BaseModel):
foo: constr(regex=r"^[^a-z]*")
foo_obj = FooSchema.parse_raw('{"foo":"ABc"}')
# 错误
# FooSchema 的 1 个验证错误
# foo
# 字符串不匹配正则表达式 "^[^a-z]*" (类型=value_error.str.regex; 模式=^[^a-z]*$)
英文:
You can use regex
(^[^a-z]*$
) parameter to validate the string if they all are in uppercase.
from pydantic import BaseModel, constr
class FooSchema(BaseModel):
foo: constr(regex=r"^[^a-z]*$")
foo_obj = FooSchema.parse_raw('{"foo":"ABc"}')
# ERROR
# 1 validation error for FooSchema
# foo
# string does not match regex "^[^a-z]*$" (type=value_error.str.regex; pattern=^[^a-z]*$)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论