Merge pull request #1430 from eugenp/sla-pr/1423-jesus-custom-validator

spring-mvc-custom-validator
This commit is contained in:
slavisa-baeldung 2017-03-20 16:00:20 +00:00 committed by GitHub
commit b4b2ad3edb
8 changed files with 214 additions and 5 deletions

View File

@ -166,7 +166,28 @@
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<!-- Validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.2.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,24 @@
package com.baeldung.customvalidator;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Documented
@Constraint(validatedBy = ContactNumberValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ContactNumberConstraint {
String message() default "Invalid phone number";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

View File

@ -0,0 +1,20 @@
package com.baeldung.customvalidator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class ContactNumberValidator implements ConstraintValidator<ContactNumberConstraint, String> {
@Override
public void initialize(ContactNumberConstraint contactNumber) {
}
@Override
public boolean isValid(String contactField, ConstraintValidatorContext cxt) {
if (contactField == null) {
return false;
}
return contactField.matches("[0-9]+") && (contactField.length() > 8) && (contactField.length() < 14);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.model;
import com.baeldung.customvalidator.ContactNumberConstraint;
public class ValidatedPhone {
@ContactNumberConstraint
private String phone;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return phone;
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.web.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import com.baeldung.model.ValidatedPhone;
@Controller
@EnableWebMvc
public class ValidatedPhoneController {
@RequestMapping(value = "/validatePhone", method = RequestMethod.GET)
public String loadFormPage(Model m) {
m.addAttribute("validatedPhone", new ValidatedPhone());
return "phoneHome";
}
@RequestMapping(value = "/addValidatePhone", method = RequestMethod.POST)
public String submitForm(@Valid ValidatedPhone validatedPhone, BindingResult result, Model m) {
if (result.hasErrors()) {
return "phoneHome";
}
m.addAttribute("message", "Successfully saved phone: " + validatedPhone.toString());
return "phoneHome";
}
}

View File

@ -1,6 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd" >
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<mvc:annotation-driven />
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
</beans>

View File

@ -0,0 +1,38 @@
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE HTML>
<html>
<head>
<title>Sample Form</title>
<style>
body { background-color: #eee; font: helvetica; }
#container { width: 500px; background-color: #fff; margin: 30px auto; padding: 30px; border-radius: 5px; }
.green { font-weight: bold; color: green; }
.message { margin-bottom: 10px; }
label {width:70px; display:inline-block;}
input { display:inline-block; margin-right: 10px; }
form {line-height: 160%; }
.hide { display: none; }
.error { color: red; font-size: 0.9em; font-weight: bold; }
</style>
</head>
<body>
<div id="container">
<h2>Phone Number</h2>
<c:if test="${not empty message}"><div class="message green">${message}</div></c:if>
<form:form action="/spring-mvc-java/addValidatePhone" modelAttribute="validatedPhone">
<label for="phoneInput">Phone: </label>
<form:input path="phone" id="phoneInput" />
<form:errors path="phone" cssClass="error" />
<br/>
<input type="submit" value="Submit" />
</form:form>
</div>
</body>
</html>

View File

@ -0,0 +1,41 @@
package com.baeldung.web.controller;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
public class CustomMVCValidatorTest {
private MockMvc mockMvc;
@Before
public void setup(){
this.mockMvc = MockMvcBuilders.standaloneSetup(new ValidatedPhoneController()).build();
}
@Test
public void givenPhonePageUri_whenMockMvc_thenReturnsPhonePage() throws Exception{
this.mockMvc.perform(get("/validatePhone")).andExpect(view().name("phoneHome"));
}
@Test
public void givenPhoneURIWithPostAndFormData_whenMockMVC_thenVerifyErrorResponse() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/addValidatePhone").
accept(MediaType.TEXT_HTML).
param("phoneInput", "123")).
andExpect(model().attributeHasFieldErrorCode("validatedPhone", "phone","ContactNumberConstraint")).
andExpect(view().name("phoneHome")).
andExpect(status().isOk()).
andDo(print());
}
}