Vaadin add icon for error message component

80 views Asked by At

I am wondering if it's possible to add an icon to the error message component that is triggered by Binder.

TextField usernameField = new TextField();

binder.forField(usernameField)
    .asRequired("Please fill this field")
    .withValidator(s -> s.length() > 3, "Username must contain at least 4 characters")
    .withValidator(s -> s.length() < 12, "Username must contain less than 12 characters")
    .bind(User::getUsername, User::setUsername);

Actual
Actual

Expected
Expected


I found this workaround, but maybe exists a more native way to do this. The problem is that it's required to have an error image .png to display the icon, which I don't really like so much. The other issue is that I can't set color for icon, I need to have 2 identical icons but with different colors(warning=yellow, error=red).

vaadin-text-field::part(error-message)::before {
    content: url('/icons/error-icon.jpg');
    margin-right: 4px;
    width: 16px;
    height: 16px;
    display: inline-block;
}
1

There are 1 answers

0
Rolf On BEST ANSWER

There's no API for doing that, and even if there was, I would still recommend a CSS-based approach, as it's much more lightweight.

As for setting a different color for the icon, you should do that through a classname on the field addClassName("warning");)

Then you have a few different options for how to change the color of the icon:

A) Switch to a different image when the classname is applied:

vaadin-text-field.warning::part(error-message)::before {
  content: url('/icons/warning-icon.jpg');
}

B) Use a font icon instead of a bitmap, e.g. with FontAwesome you could do something like this:

vaadin-text-field::part(error-message)::before {
    font-family: "Font Awesome 6 Free";
    content: '\f5b3';
    display: inline-block;
}

/* Different color for warning state */
vaadin-text-field.warning::part(error-message)::before {
    color: rgb(156, 122, 0);
}

Or you could use the built-in Lumo Icons font:

vaadin-text-field::part(error-message)::before {
    font-family: "lumo-icons";
    content: var(--lumo-icons-error);
    display: inline-block;
}

C) Use an SVG image as a mask over a background color you can change.