django-widget-tweaks icon indicating copy to clipboard operation
django-widget-tweaks copied to clipboard

Is it possible to add is-valid class after validation

Open xflyer11 opened this issue 4 years ago • 3 comments

I understand there is a way to add error css class, is there a way to add the is-valid class after validation?

xflyer11 avatar Sep 01 '21 23:09 xflyer11

{%if form.is_valid %}
{{form.field|add_class="is-valid"}}
{% endif %}

zodman avatar Sep 02 '21 19:09 zodman

with render_field i am currently doing it like this:

{% if form.myfield.errors %}
    {% render_field form.myfield class+="form-control is-invalid" title=form.myfield.label %}
{% else %}
    {% render_field form.myfield class+="form-control" title=form.myfield.label %}
{% endif %}

lot's of repeated code. is there a better way?

i'd imagine something like an "error_class" argument would be nice, eg:

{% render_field form.myfield class+="form-control" error_class="is-invalid" title=form.myfield.label %}

fdemmer avatar Sep 11 '21 10:09 fdemmer

I found this ticket right after submitting #126 , as far as I can tell,

{% if form.myfield.errors %}
    {% render_field form.myfield class+="form-control is-invalid" title=form.myfield.label %}
{% else %}
    {% render_field form.myfield class+="form-control" title=form.myfield.label %}
{% endif %}

does not handle the case of valid field from validated form, and we need something like

{% if form.myfield.errors %}
    {% render_field form.myfield class+="form-control is-invalid" title=form.myfield.label %}
{% elif form.is_bound %}
    {% render_field form.myfield class+="form-control is-valid" title=form.myfield.label %}
{% else %}
    {% render_field form.myfield class+="form-control" title=form.myfield.label %}
{% endif %}

This is quite tedious if we are doing this for all fields, #126 proposes the shortening of the above to

{% render_field form.myfield|add_class:"form-control"|add_valid_class:"form-control is-valid"|add_error_class:"form-control is-invalid" title=form.myfield.label %}

or even better

{% with WIDGET_ERROR_CLASS='is-invalid' WIDGET_VALID_CLASS="is-valid" %}
    {% render_field form.field1|add_class:"form-control" %}
{% endwith %}

BoPeng avatar May 02 '22 06:05 BoPeng