def set_invalid(field, render_kw=None):
    """
    Returns *render_kw* with `invalid` added to *class* on validation errors.

    Set (or appends) 'invalid' to the fields CSS class(es), if the *field* got
    any errors. 'invalid' is also set by browsers if they detect errors on a
    field.

    """
    if render_kw is None:
        render_kw = {}
    if field.errors:
        classes = render_kw.get('class') or render_kw.pop('class_', '')
        if classes:
            render_kw['class'] = 'invalid {}'.format(classes)
        else:
            render_kw['class'] = 'invalid'
    return render_kw