簡體   English   中英

使用 WTForms 和 python 進行正則表達式驗證

[英]Regex validation with WTForms and python

這是我的代碼:

class CreateUser(Form):
    username = StringField('Username', [
        validators.Regexp('\w+', message="Username must contain only letters numbers or underscore"),
        validators.Length(min=5, max=25, message="Username must be betwen 5 & 25 characters")

    ])

    password = PasswordField('New Password', [
        validators.DataRequired(), 
        validators.EqualTo('confirm', message='Passwords must match')
    ])

    confirm  = PasswordField('Repeat Password')

所以問題存在於第 3 行。我希望用戶名只能是字母數字字符。 出於某種原因,這個正則表達式只檢查第一個字符。 + 符號在這里不起作用有什么原因嗎? 謝謝。

將正則表達式替換為

'^\w+$'

解決了這個問題。

我知道這是很久以前的回答,但我發現在 WTForms 上提供字母數字驗證的另一個選項是 AlphaNumeric()

from wtforms_validators import AlphaNumeric
...

class SignupForm(Form):
    login_id = StringField('login Id', [DataRequired(), AlphaNumeric()])

更多細節在這里https://pypi.org/project/wtforms-validators/

@mpn 解決方案工作正常,但我想知道為什么\\w+不匹配整個字符串。

在 wtforms 的Regexp 類中__call__方法中,您將看到self.regex.match(field.data or '')將被調用。 re.py 的文檔說明了關於re.match內容:

如果 string 開頭的零個或多個字符與正則表達式模式匹配,則返回相應的匹配對象。

因此,我們必須使用^來匹配字符串的開頭,使用$來匹配字符串的結尾。 文檔中閱讀有關特殊字符的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM