如何将 Bootstrap 验证添加到 WTForms [英] How to add Bootstrap Validation to WTForms

查看:35
本文介绍了如何将 Bootstrap 验证添加到 WTForms的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 WTForms 与 Flask 结合使用,我想集成 Bootstrap Form Validation 用于我的表单中的错误.我有一个基本的登录表单设置,如下所示:

class LoginForm(FlaskForm):登录表单."""电子邮件 = 电子邮件字段(电子邮件地址",验证器=[DataRequired(), Email(), Length(min=6, max=40)])密码 = 密码字段(密码",验证器=[DataRequired()])def __init__(self, *args, **kwargs):"""创建实例."""super(LoginForm, self).__init__(*args, **kwargs)self.user = 无定义验证(自我):"""验证表单."""initial_validation = super(LoginForm, self).validate()如果不是initial_validation:返回错误self.user = User.query.filter_by(email=self.email.data).first()如果不是 self.user:self.email.errors.append("未知电子邮件地址!")返回错误如果不是 self.user.check_password(self.password.data):self.password.errors.append("密码无效!")返回错误如果不是 self.user.verified:self.email.errors.append("请验证您的电子邮件地址!")返回错误返回真

我的 login.html 模板是这样设置的:

{{ form.csrf_token }}<div class="form-group">{{ form.email.label(class_="form-control-label") }}<div class="input-group input-group-merge"><div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-user"></i></span>

{{ form.email(placeholder="name@example.com", class_="form-control") }}

<div class="form-group mb-4"><div class="d-flex align-items-center justify-content-between"><div>{{ form.password.label(class_="form-control-label") }}

<div class="mb-2"><a href="{{ url_for('public.recover') }}" class="small text-muted text-underline--dashed border-primary">密码丢失?</a>

<div class="input-group input-group-merge"><div class="input-group-prepend"><span class="input-group-text"><i class="fas fa-key"></i></span>

{{ form.password(placeholder="Password", class_="form-control") }}<div class="input-group-append" onclick="togglePassword()"><span class="input-group-text"><i class="fas fa-eye"></i></span>

<div class="row mt-4"><div class="col-md-auto mt-1 mb-2" align="center"><button type="submit" class="btn btn-sm btn-primary btn-icon rounded-pill"><span class="btn-inner--text">登录</span><span class="btn-inner--icon"><i class="fas fa-long-arrow-alt-right"></i></span>

<div class="col-md-auto text-center mt-2"><p class="text-secondary-dark">或</p>

<div class="col-md-auto" align="center"><button type="button" class="btn btn-md btn-secondary btn-icon-only"><span class="btn-inner--icon"><i class="fab fa-google"></i></span><button type="button" class="btn btn-md btn-secondary btn-icon-only"><span class="btn-inner--icon"><i class="fab fa-linkedin"></i></span>

</表单>

我想显示我使用 WTForms 验证的错误,但我不确定如何将原始表单元素的类更改为 is-invalidis-valid,以及如何为每个错误创建标签.我研究过宏,但它们似乎也无法修改表单元素.

有人能指出我正确的方向吗?

解决方案

@cizario 的回答 是一个很好的开始.但是,我找到了更好的错误实现.使用 WTForm 的自定义小部件,您可以获得以下小部件:

from wtforms.widgets import PasswordInput, CheckboxInput, TextInput从 wtforms.widgets.html5 导入 EmailInput类 BootstrapVerifyEmail(EmailInput):"电子邮件的引导验证程序""def __init__(self, error_class=uis-invalid"):super(BootstrapVerifyEmail, self).__init__()self.error_class = error_classdef __call__(self, field, **kwargs):如果 field.errors:c = kwargs.pop("class", "") 或 kwargs.pop("class_", "")kwargs[class"] = u%s %s"% (self.error_class, c)return super(BootstrapVerifyEmail, self).__call__(field, **kwargs)类 BootstrapVerifyPassword(PasswordInput):"密码的引导验证程序""def __init__(self, error_class=uis-invalid"):super(BootstrapVerifyPassword, self).__init__()self.error_class = error_classdef __call__(self, field, **kwargs):如果 field.errors:c = kwargs.pop("class", "") 或 kwargs.pop("class_", "")kwargs[class"] = u%s %s"% (self.error_class, c)return super(BootstrapVerifyPassword, self).__call__(field, **kwargs)类 BootstrapVerifyBoolean(CheckboxInput):"Bootstrap Validator for boolean""def __init__(self, error_class=uis-invalid"):super(BootstrapVerifyBoolean, self).__init__()self.error_class = error_classdef __call__(self, field, **kwargs):如果 field.errors:c = kwargs.pop("class", "") 或 kwargs.pop("class_", "")kwargs[class"] = u%s %s"% (self.error_class, c)return super(BootstrapVerifyBoolean, self).__call__(field, **kwargs)类 BootstrapVerifyText(TextInput):"文本的引导程序验证器""def __init__(self, error_class=uis-invalid"):super(BootstrapVerifyText, self).__init__()self.error_class = error_classdef __call__(self, field, **kwargs):如果 field.errors:c = kwargs.pop("class", "") 或 kwargs.pop("class_", "")kwargs[class"] = u%s %s"% (self.error_class, c)return super(BootstrapVerifyText, self).__call__(field, **kwargs)

这将添加无效标签,以便引导程序可以将其标记为无效.在 HTML 中,执行以下操作以添加错误消息:

{{ login_user_form.email.label(class_=form-control-label") }}<div class="input-group input-group-merge"><div class="input-group-prepend"><span class="input-group-text";id=user"><i class=fas fa-user"></i></span>

{{ login_user_form.email(placeholder=name@example.com", class_=form-control", **{aria-scribedby": inputGroupPrepend3", required": ";}) }}{% 用于 login_user_form.email.errors 中的错误 %}<div class="invalid-feedback">{{ error }}</div>{% 结束为 %}

I am using WTForms in conjunction with Flask and I would like to integrate the Bootstrap Form Validation for errors in my form. I have a basic login form setup something like this:

class LoginForm(FlaskForm):
    """Login form."""

    email = EmailField(
        "Email Address", validators=[DataRequired(), Email(), Length(min=6, max=40)]
    )
    password = PasswordField(
        "Password", validators=[DataRequired()]
    )

    def __init__(self, *args, **kwargs):
        """Create instance."""
        super(LoginForm, self).__init__(*args, **kwargs)
        self.user = None

    def validate(self):
        """Validate the form."""
        initial_validation = super(LoginForm, self).validate()
        if not initial_validation:
            return False

        self.user = User.query.filter_by(email=self.email.data).first()
        if not self.user:
            self.email.errors.append("Unknown email address!")
            return False

        if not self.user.check_password(self.password.data):
            self.password.errors.append("Invalid password!")
            return False

        if not self.user.verified:
            self.email.errors.append("Please verify your email address!")
            return False
        return True

My login.html template is setup like this:

<form method="POST" action="{{ url_for('public.login') }}" role="form">
                  {{ form.csrf_token }}
                  <div class="form-group">
                    {{ form.email.label(class_="form-control-label") }}
                    <div class="input-group input-group-merge">
                      <div class="input-group-prepend">
                        <span class="input-group-text"><i class="fas fa-user"></i></span>
                      </div>
                      {{ form.email(placeholder="name@example.com", class_="form-control") }}
                    </div>
                  </div>
                  <div class="form-group mb-4">
                    <div class="d-flex align-items-center justify-content-between">
                      <div>
                        {{ form.password.label(class_="form-control-label") }}
                      </div>
                      <div class="mb-2">
                        <a href="{{ url_for('public.recover') }}" class="small text-muted text-underline--dashed border-primary">Lost password?</a>
                      </div>
                    </div>
                    <div class="input-group input-group-merge">
                      <div class="input-group-prepend">
                        <span class="input-group-text"><i class="fas fa-key"></i></span>
                      </div>
                      {{ form.password(placeholder="Password", class_="form-control") }}
                      <div class="input-group-append" onclick="togglePassword()">
                        <span class="input-group-text">
                          <i class="fas fa-eye"></i>
                        </span>
                      </div>
                    </div>
                  </div>
                  <div class="row mt-4">
                    <div class="col-md-auto mt-1 mb-2" align="center">
                      <button type="submit" class="btn btn-sm btn-primary btn-icon rounded-pill">
                        <span class="btn-inner--text">Sign in</span>
                        <span class="btn-inner--icon"><i class="fas fa-long-arrow-alt-right"></i></span>
                      </button>
                    </div>
                    <div class="col-md-auto text-center mt-2">
                      <p class="text-secondary-dark">or</p>
                      </div>
                    <div class="col-md-auto" align="center">
                      <button type="button" class="btn btn-md btn-secondary btn-icon-only">
                          <span class="btn-inner--icon">
                              <i class="fab fa-google"></i>
                          </span>
                      </button>

                      <button type="button" class="btn btn-md btn-secondary btn-icon-only">
                          <span class="btn-inner--icon">
                              <i class="fab fa-linkedin"></i>
                          </span>
                      </button>
                    </div>
                  </div>
                </form>

I would like to display the errors that I validate using WTForms, but I am unsure of how to change the class of the original form element to is-invalid or is-valid, and how to create the labels for each error. I have looked into macros, but they don't seem to be able to modify the form element either.

Can someone point me in the right direction?

解决方案

@cizario's answer is a great start. However, I found a better implementation for the errors. Using WTForm's Custom Widgets, you get the following widgets:

from wtforms.widgets import PasswordInput, CheckboxInput, TextInput
from wtforms.widgets.html5 import EmailInput


class BootstrapVerifyEmail(EmailInput):
    """Bootstrap Validator for email"""

    def __init__(self, error_class=u"is-invalid"):
        super(BootstrapVerifyEmail, self).__init__()
        self.error_class = error_class

    def __call__(self, field, **kwargs):
        if field.errors:
            c = kwargs.pop("class", "") or kwargs.pop("class_", "")
            kwargs["class"] = u"%s %s" % (self.error_class, c)
        return super(BootstrapVerifyEmail, self).__call__(field, **kwargs)


class BootstrapVerifyPassword(PasswordInput):
    """Bootstrap Validator for password"""

    def __init__(self, error_class=u"is-invalid"):
        super(BootstrapVerifyPassword, self).__init__()
        self.error_class = error_class

    def __call__(self, field, **kwargs):
        if field.errors:
            c = kwargs.pop("class", "") or kwargs.pop("class_", "")
            kwargs["class"] = u"%s %s" % (self.error_class, c)
        return super(BootstrapVerifyPassword, self).__call__(field, **kwargs)


class BootstrapVerifyBoolean(CheckboxInput):
    """Bootstrap Validator for boolean"""

    def __init__(self, error_class=u"is-invalid"):
        super(BootstrapVerifyBoolean, self).__init__()
        self.error_class = error_class

    def __call__(self, field, **kwargs):
        if field.errors:
            c = kwargs.pop("class", "") or kwargs.pop("class_", "")
            kwargs["class"] = u"%s %s" % (self.error_class, c)
        return super(BootstrapVerifyBoolean, self).__call__(field, **kwargs)


class BootstrapVerifyText(TextInput):
    """Bootstrap Validator for text"""

    def __init__(self, error_class=u"is-invalid"):
        super(BootstrapVerifyText, self).__init__()
        self.error_class = error_class

    def __call__(self, field, **kwargs):
        if field.errors:
            c = kwargs.pop("class", "") or kwargs.pop("class_", "")
            kwargs["class"] = u"%s %s" % (self.error_class, c)
        return super(BootstrapVerifyText, self).__call__(field, **kwargs)

This will add the invalid tag so that bootstrap can mark it as invalid. In the HTML, do something like this to add the error message:

{{ login_user_form.email.label(class_="form-control-label") }}
<div class="input-group input-group-merge">
    <div class="input-group-prepend">
        <span class="input-group-text" id="user"><i class="fas fa-user"></i></span>
    </div>
    {{ login_user_form.email(placeholder="name@example.com", class_="form-control", **{"aria-describedby": "inputGroupPrepend3", "required": ""}) }}
    {% for error in login_user_form.email.errors %}
        <div class="invalid-feedback">{{ error }}</div>
    {% endfor %}
</div>

这篇关于如何将 Bootstrap 验证添加到 WTForms的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆