Skip to content

Commit 3504296

Browse files
lor6pivovarit
authored andcommitted
custom class validation (eugenp#1832)
* custom class validation * formatting
1 parent 44b0f6b commit 3504296

6 files changed

Lines changed: 202 additions & 2 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.baeldung.customvalidator;
2+
3+
import java.lang.annotation.ElementType;
4+
import java.lang.annotation.Retention;
5+
import java.lang.annotation.RetentionPolicy;
6+
import java.lang.annotation.Target;
7+
8+
import javax.validation.Constraint;
9+
import javax.validation.Payload;
10+
11+
@Constraint(validatedBy = FieldsValueMatchValidator.class)
12+
@Target({ ElementType.TYPE })
13+
@Retention(RetentionPolicy.RUNTIME)
14+
public @interface FieldsValueMatch {
15+
16+
String message() default "Fields values don't match!";
17+
18+
Class<?>[] groups() default {};
19+
20+
Class<? extends Payload>[] payload() default {};
21+
22+
String field();
23+
24+
String fieldMatch();
25+
26+
@Target({ ElementType.TYPE })
27+
@Retention(RetentionPolicy.RUNTIME)
28+
@interface List {
29+
FieldsValueMatch[] value();
30+
}
31+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.baeldung.customvalidator;
2+
3+
import javax.validation.ConstraintValidator;
4+
import javax.validation.ConstraintValidatorContext;
5+
6+
import org.springframework.beans.BeanWrapperImpl;
7+
8+
public class FieldsValueMatchValidator implements ConstraintValidator<FieldsValueMatch, Object> {
9+
10+
private String field;
11+
private String fieldMatch;
12+
13+
public void initialize(FieldsValueMatch constraintAnnotation) {
14+
this.field = constraintAnnotation.field();
15+
this.fieldMatch = constraintAnnotation.fieldMatch();
16+
}
17+
18+
public boolean isValid(Object value, ConstraintValidatorContext context) {
19+
20+
Object fieldValue = new BeanWrapperImpl(value).getPropertyValue(field);
21+
Object fieldMatchValue = new BeanWrapperImpl(value).getPropertyValue(fieldMatch);
22+
23+
if (fieldValue != null) {
24+
return fieldValue.equals(fieldMatchValue);
25+
} else {
26+
return fieldMatchValue == null;
27+
}
28+
29+
}
30+
31+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.baeldung.model;
2+
3+
import com.baeldung.customvalidator.FieldsValueMatch;
4+
5+
@FieldsValueMatch.List({
6+
@FieldsValueMatch(field = "password", fieldMatch = "verifyPassword", message = "Passwords do not match!"),
7+
@FieldsValueMatch(field = "email", fieldMatch = "verifyEmail", message = "Email addresses do not match!")
8+
})
9+
public class NewUserForm {
10+
private String email;
11+
private String verifyEmail;
12+
private String password;
13+
private String verifyPassword;
14+
15+
public NewUserForm() {
16+
}
17+
18+
public NewUserForm(String email, String verifyEmail, String password, String verifyPassword) {
19+
super();
20+
this.email = email;
21+
this.verifyEmail = verifyEmail;
22+
this.password = password;
23+
this.verifyPassword = verifyPassword;
24+
}
25+
26+
public String getEmail() {
27+
return email;
28+
}
29+
30+
public void setEmail(String email) {
31+
this.email = email;
32+
}
33+
34+
public String getVerifyEmail() {
35+
return verifyEmail;
36+
}
37+
38+
public void setVerifyEmail(String verifyEmail) {
39+
this.verifyEmail = verifyEmail;
40+
}
41+
42+
public String getPassword() {
43+
return password;
44+
}
45+
46+
public void setPassword(String password) {
47+
this.password = password;
48+
}
49+
50+
public String getVerifyPassword() {
51+
return verifyPassword;
52+
}
53+
54+
public void setVerifyPassword(String verifyPassword) {
55+
this.verifyPassword = verifyPassword;
56+
}
57+
58+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.baeldung.web.controller;
2+
3+
import javax.validation.Valid;
4+
5+
import org.springframework.stereotype.Controller;
6+
import org.springframework.ui.Model;
7+
import org.springframework.validation.BindingResult;
8+
import org.springframework.web.bind.annotation.GetMapping;
9+
import org.springframework.web.bind.annotation.PostMapping;
10+
11+
import com.baeldung.model.NewUserForm;
12+
13+
@Controller
14+
public class NewUserController {
15+
16+
@GetMapping("/user")
17+
public String loadFormPage(Model model) {
18+
model.addAttribute("newUserForm", new NewUserForm());
19+
return "userHome";
20+
}
21+
22+
@PostMapping("/user")
23+
public String submitForm(@Valid NewUserForm newUserForm, BindingResult result, Model model) {
24+
if (result.hasErrors()) {
25+
return "userHome";
26+
}
27+
28+
model.addAttribute("message", "Valid form");
29+
return "userHome";
30+
}
31+
}

‎spring-mvc-java/src/main/java/com/baeldung/web/controller/ValidatedPhoneController.java‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,10 @@
66
import org.springframework.validation.BindingResult;
77
import org.springframework.web.bind.annotation.GetMapping;
88
import org.springframework.web.bind.annotation.PostMapping;
9-
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
109

1110
import javax.validation.Valid;
1211

1312
@Controller
14-
@EnableWebMvc
1513
public class ValidatedPhoneController {
1614

1715
@GetMapping("/validatePhone")
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.baeldung.web.controller;
2+
3+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
4+
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
5+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
6+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
7+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
8+
9+
import org.junit.Before;
10+
import org.junit.Test;
11+
import org.springframework.http.MediaType;
12+
import org.springframework.test.web.servlet.MockMvc;
13+
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
14+
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
15+
16+
public class ClassValidationMvcTest {
17+
private MockMvc mockMvc;
18+
19+
@Before
20+
public void setup(){
21+
this.mockMvc = MockMvcBuilders.standaloneSetup(new NewUserController()).build();
22+
}
23+
24+
@Test
25+
public void givenMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception {
26+
this.mockMvc.perform(MockMvcRequestBuilders.post("/user")
27+
.accept(MediaType.TEXT_HTML)
28+
.param("email", "john@yahoo.com")
29+
.param("verifyEmail", "john@yahoo.com")
30+
.param("password", "pass")
31+
.param("verifyPassword", "pass"))
32+
.andExpect(model().attribute("message", "Valid form"))
33+
.andExpect(view().name("userHome"))
34+
.andExpect(status().isOk())
35+
.andDo(print());
36+
}
37+
38+
@Test
39+
public void givenNotMatchingEmailPassword_whenPostNewUserForm_thenOk() throws Exception {
40+
this.mockMvc.perform(MockMvcRequestBuilders.post("/user")
41+
.accept(MediaType.TEXT_HTML)
42+
.param("email", "john@yahoo.com")
43+
.param("verifyEmail", "john@yahoo.commmm")
44+
.param("password", "pass")
45+
.param("verifyPassword", "passsss"))
46+
.andExpect(model().errorCount(2))
47+
.andExpect(view().name("userHome"))
48+
.andExpect(status().isOk())
49+
.andDo(print());
50+
}
51+
}

0 commit comments

Comments
 (0)