2013-03-08 70 views
2

我想與蟒蛇妖嬈,也許這樣的事情來驗證網址和電子郵件輸入數據:我如何驗證網址和電子郵件與python性感?

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

查看源代碼,我看到妖嬈具有一個內置的網址功能,在電子郵件的情況下,它沒有,所以我想建立自己的,問題是我不知道必須在模式內調用這個函數。

回答

6

UPDATE:現在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' : "[email protected]"}) # <-- this should validate the email address 
+0

這個規則表達式不接受電子郵件一樣[email protected],這是有效的。 – 2013-08-20 23:40:12

+0

那麼你可以簡單地擴展表達式:''[\ w \。\ - \ +] * @ [\ w \。\ - ] * \。\ w +「'...瞧。 – 2013-09-13 07:42:47

+0

如果驗證基於正則表達式,則可以直接使用「匹配」函數,而不是編寫整個驗證器。 – jcollado 2015-04-17 10:23:01