Adding pet name validation on edit Pet

This commit is contained in:
bijomutta 2023-07-11 21:39:36 +02:00 committed by Dave Syer
parent 3be289517d
commit 3a6127557d
2 changed files with 13 additions and 4 deletions

View file

@ -132,10 +132,9 @@ public class Owner extends Person {
public Pet getPet(String name, boolean ignoreNew) {
name = name.toLowerCase();
for (Pet pet : getPets()) {
if (!ignoreNew || !pet.isNew()) {
String compName = pet.getName();
compName = compName == null ? "" : compName.toLowerCase();
if (compName.equals(name)) {
String compName = pet.getName();
if (compName != null && compName.equalsIgnoreCase(name)) {
if (!ignoreNew || !pet.isNew()) {
return pet;
}
}

View file

@ -114,6 +114,16 @@ class PetController {
@PostMapping("/pets/{petId}/edit")
public String processUpdateForm(@Valid Pet pet, BindingResult result, Owner owner, ModelMap model) {
String petName = pet.getName();
// checking if the pet name already exist for the owner
if (StringUtils.hasLength(petName)) {
Pet existingPet = owner.getPet(petName.toLowerCase(), false);
if (existingPet != null && existingPet.getId() != pet.getId()) {
result.rejectValue("name", "duplicate", "already exists");
}
}
LocalDate currentDate = LocalDate.now();
if (pet.getBirthDate() != null && pet.getBirthDate().isAfter(currentDate)) {
result.rejectValue("birthDate", "typeMismatch.birthDate");