Forms are an essential component in web applications, and their validation is crucial for a good user experience. If you've been looking for a streamlined approach to React form validation, you're in the right place.
With the release of Hilla 2.2, you can now effortlessly build forms using the new useForm
hook. This post explores how this hook simplifies form validation and submission when using React and Spring Boot together.
Server-side form model definition for React form validation
Defining the form model on your Spring Boot server is the first step. You can annotate any Java class like a DTO, entity, or record for form validation:
@BrowserCallable
public class PersonService {
public record Person(
@Size(min = 3, max = 50)
String firstName,
String lastName,
@Email
String email
) {}
public Person findById(int id) {
// query database
}
public Person save(Person person) {
// persist to database
}
}
This Java model generates a TypeScript model consumed by the useForm
hook. Validation rules like @Size
and @Email
are automatically applied.
Building a form in React with built-in validation
First, import the useForm
hook from Hilla's form library:
import { useForm } from "@hilla/react-form";
Set up the useForm
with a model and an options object for React form validation:
const { model, field, read, submit } = useForm(PersonModel, {
onSubmit: async (person) => {
await PersonService.save(person);
},
});
Then use field
and model
to bind the inputs to the Person
model:
<TextField label="First name" {...field(model.firstName)} />
<TextField label="Last name" {...field(model.lastName)} />
<TextField label="Email" {...field(model.email)} />
<Button onClick={submit}>Submit</Button>
You can populate the initial form values using the read
method:
useEffect(() => {
PersonService.findById(1).then((person) => {
read(person);
});
}, []);
The submit
method handles form submission and invokes the onSubmit
callback.
Validation rules set on the Spring Boot server automatically apply when using useForm
for React form validation.
You can even customize validation messages:
@Size(min = 3, max = 50, message = "First name must be 3-50 chars")
String firstName;
Submitting a validated form in React
The onSubmit
callback is invoked when the submit button is clicked. Validation is automatically re-checked before the data is sent to the server.
const { submit } = useForm(/*..*/, {
onSubmit: async (person) => {
await PersonService.save(person);
}
});
Wrap-up
Hilla 2.2's new form library offers an efficient way to implement React form validation. It centralizes the form model on the Spring Boot server, while the useForm
hook manages validation, submission, and more on the React frontend.