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

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

问题描述

我正在将WTForms与Flask结合使用,我想集成

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

我的login.html模板的设置如下:

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>

我想显示我使用WTForms验证的错误,但是我不确定如何将原始表单元素的类更改为is-invalidis-valid,以及如何为每个错误创建标签.我研究了宏,但它们似乎也无法修改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的答案是一个很好的开始.但是,我发现了一个更好的错误实现.使用 WTForm的自定义小部件,您将获得以下小部件:

@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:

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)

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

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天全站免登陆