我无法对我的 mongoengine 模型中的输入数据执行验证 class

I'm not able to perform validation for the input data in my mongoengine model class

class TextBoxValues(DynamicDocument):
    entity_id = StringField(max_length=200, required=True) 
    textbox_type = StringField(max_length=1000, required=True)  
    regexp = re.compile('[A-Za-z]')
    entity_value = StringField(regex=regexp,max_length=None, required=True) 

我正在使用正则表达式参数执行验证,但它对我不起作用,它仍然接受任何格式的输入,为什么?

提供给 StringField(regex=) 的正则表达式实际上应该是一个字符串,但如果您给它一个已编译的正则表达式,它也可以工作。

问题实际上是你的正则表达式。它应该是 regexp=r'^[A-Za-z]+$' 正如@wiktor-stribiżew 在评论中建议的那样。

下面的最小示例演示了正则表达式按预期工作

from mongoengine import *
connect()    # connect to 'test' database

class TextBoxValues(Document):
    entity_value = StringField(regex=r'^[A-Za-z]+$')

TextBoxValues(entity_value="AZaz").save() # passes validation

TextBoxValues(entity_value="AZaz1").save() # raises ValidationError (String value did not match validation regex: ['entity_value'])