How to add Bootstrap Validation to WTForms

纵然是瞬间 提交于 2020-07-19 16:38:51

问题


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?


回答1:


i faced the same problem and i wanted to avoid the use of any third package (flask-bootstrap) and i came up with this simple solution:

<div class="form-group">
  {{ form.email.label }} <span class="text-danger">*</span>

  {# her #}
  {{ form.email(class="form-control" + (" is-invalid" if form.email.errors else "") + " rounded-0 shadow-none", **{"placeholder": "Your Email", "aria-describedby": "emailHelp", "autocomplete": "off"}) }}


  <small id="emailHelp" class="form-text text-muted">We'll never share your data with anyone else.</small>

  {% if form.email.errors %}
    {% for error in form.email.errors %}
      <div class="invalid-feedback">{{ error }}</div>
    {% endfor %}
  {% endif %}
</div>

the trick is to use a simple ternary expression combined with string concatenation.




回答2:


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

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>



回答3:


When rendering your template using render_template, pass the 'is-valid' class to all the elements you want. Use this

class = '{{email_valid_class}} all other classes here'

Then in python return render_template('login.html',email_valid_class='is-valid')



来源:https://stackoverflow.com/questions/61241168/how-to-add-bootstrap-validation-to-wtforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!