Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

In this tutorial, we look at how we can define custom attributes in HTML5 tags using Thymeleaf. It is a template engine framework which allows plain HTML to be used to display dynamic data.

For an introductory article on Thymeleaf or its integration with Spring refer to this link.

2. Custom Attributes in HTML5

Sometimes we may require extra information in HTML pages to do some processing on the client-side. For instance, we may want to save additional data in form input tags so that we can use them while submitting the form using AJAX.

Likewise, we may want to display custom validation error messages to a user filling a form.

In any case, we can supply this additional data by using HTML 5’s custom attributes. Custom attributes can be defined in an HTML tag using the data- prefix.

Now, let’s see how we can define these attributes using the default dialect in Thymeleaf.

3. Custom HTML Attributes in Thymeleaf

We can specify a custom attribute in an HTML tag using the syntax:

th:data-<attribute_name>=""

Let’s create a simple form which allows a student to register for a course to see things in action:

<form action="#" th:action="@{/registerCourse}" th:object="${course}"
    method="post" onsubmit="return validateForm();">
    <span id="errormesg" style="color: red"></span> <span
      style="font-weight: bold" th:text="${successMessage}"></span>
    <table>
        <tr>
            <td>
                <label th:text="#{msg.courseName}+': '"></label>
            </td>
            <td>
                <select id="course" th:field="*{name}">
                    <option th:value="''" th:text="'Select'"></option>
                    <option th:value="'Mathematics'" th:text="'Mathematics'"></option>
                    <option th:value="'History'" th:text="'History'"></option>
                </select></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit" /></td>
        </tr>
    </table>
</form>

This form contains a single dropdown with the available courses and a submit button.

Let’s say we want to show a custom error message to the user if they click on submit without selecting a course.

We can save the error message as a custom attribute in the select tag and create a JavaScript function to validate its value on submitting the form.

The updated select tag looks something like this:

<select id="course" th:field="*{name}" th:data-validation-message="#{msg.courseName.mandatory}">

Here, we’re fetching the error message from the resource bundle.

Now, when the user submits the form without selecting a valid option, this JavaScript function will display an error message to the user:

function validateForm() {
    var e = document.getElementById("course");
    var value = e.options[e.selectedIndex].value;
    if (value == '') {
        var error = document.getElementById("errormesg");
        error.textContent = e.getAttribute('data-validation-message');
        return false;
    }
    return true;
}

Similarly, we can add multiple custom attributes to HTML tags by defining th:data-* attribute for each one of them.

3. Conclusion

In this quick article, we explored how we can leverage Thymeleaf’s support to add custom attributes in HTML5 templates.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW