简体   繁体   English

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

[英]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) 

I was using the regex parameter to perform validation which is not working for me,it still takes input in any format, why?我正在使用正则表达式参数来执行对我不起作用的验证,它仍然接受任何格式的输入,为什么?

The regex to provide to StringField(regex=) should in fact be a string but it also work if you give it a compiled regex.提供给StringField(regex=)实际上应该是一个字符串,但如果你给它一个编译的正则表达式它也可以工作。

The problem is your regex actually.问题实际上是您的正则表达式。 It should be regexp=r'^[A-Za-z]+$' as @wiktor-stribiżew suggested in the comment.正如@wiktor-stribiżew 在评论中所建议的那样,它应该是regexp=r'^[A-Za-z]+$'

The minimal example below demonstrates that the regex works as expected下面的最小示例表明正则表达式按预期工作

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'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM