Add user friendly validation messages

This commit is contained in:
lukasdooo 2024-02-05 16:41:47 +01:00
parent 836d111e99
commit 73e7aef4ea
4 changed files with 10 additions and 9 deletions

View file

@ -28,11 +28,11 @@ import jakarta.validation.constraints.NotBlank;
public class Person extends BaseEntity {
@Column(name = "first_name")
@NotBlank
@NotBlank(message = "First Name cannot be blank")
private String firstName;
@Column(name = "last_name")
@NotBlank
@NotBlank(message = "Last Name cannot be blank")
private String lastName;
public String getFirstName() {

View file

@ -18,6 +18,7 @@ package org.springframework.samples.petclinic.owner;
import java.util.ArrayList;
import java.util.List;
import jakarta.validation.constraints.Pattern;
import org.springframework.core.style.ToStringCreator;
import org.springframework.samples.petclinic.model.Person;
import org.springframework.util.Assert;
@ -47,16 +48,16 @@ import jakarta.validation.constraints.NotBlank;
public class Owner extends Person {
@Column(name = "address")
@NotBlank
@NotBlank(message = "Address cannot be blank")
private String address;
@Column(name = "city")
@NotBlank
@NotBlank(message = "City cannot be blank")
private String city;
@Column(name = "telephone")
@NotBlank
@Digits(fraction = 0, integer = 10)
@NotBlank(message = "Telephone cannot be blank")
@Pattern(regexp = "\\d{10}", message = "Telephone must be a 10-digit number")
private String telephone;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)

View file

@ -54,7 +54,7 @@ class ValidatorTests {
assertThat(constraintViolations).hasSize(1);
ConstraintViolation<Person> violation = constraintViolations.iterator().next();
assertThat(violation.getPropertyPath().toString()).isEqualTo("firstName");
assertThat(violation.getMessage()).isEqualTo("must not be blank");
assertThat(violation.getMessage()).isEqualTo("First Name cannot be blank");
}
}

View file

@ -117,7 +117,7 @@ class OwnerControllerTests {
.param("lastName", "Bloggs")
.param("address", "123 Caramel Street")
.param("city", "London")
.param("telephone", "01316761638"))
.param("telephone", "0123456789"))
.andExpect(status().is3xxRedirection());
}
@ -188,7 +188,7 @@ class OwnerControllerTests {
.param("lastName", "Bloggs")
.param("address", "123 Caramel Street")
.param("city", "London")
.param("telephone", "01616291589"))
.param("telephone", "0123456789"))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/owners/{ownerId}"));
}