如何验证字符串字段是否全部大写,而不使用自定义验证程序

huangapple go评论90阅读模式
英文:

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]*$)

huangapple
  • 本文由 发表于 2023年2月6日 16:47:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75359078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定