如何使用Python Voluptuous验证URL和邮箱?

2 投票
1 回答
3122 浏览
提问于 2025-04-17 18:23

我想用Python的voluptuous库来验证网址和电子邮件的输入数据,可能像这样:

schema = Schema({
    Required('url'): All(str, Url()),
    Required('email'): All(str, Email())
})

我查看了源代码,发现voluptuous有一个内置的Url函数,但对于电子邮件却没有。所以我想自己写一个,问题是我不知道怎么在schema里面调用这些函数。

1 个回答

9

更新: 现在 voluptuous 已经有了邮箱验证功能。

你可以像这样编写自己的验证器:

import re
from voluptuous import All, Invalid, Required, Schema

def Email(msg=None):
    def f(v):
        if re.match("[\w\.\-]*@[\w\.\-]*\.\w+", str(v)):
            return str(v)
        else:
            raise Invalid(msg or ("incorrect email address"))
    return f

schema = Schema({
        Required('email') : All(Email())
    })

schema({'email' : "invalid_email.com"}) # <-- this will result in a MultipleInvalid Exception
schema({'email' : "valid@email.com"}) # <-- this should validate the email address

撰写回答