Bindingresult is not working properly with Validation

Asked

Viewed 269 times

0

My goal is to register an older person with a valid name, through validation.

The class Person.java:

package br.com.Test.domain;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

public class Person {

    @NotBlank
    @Size(min= 2, max = 20, message="O Tamanho deve ser entre 2 a 20 caracteres")
    @Pattern(regexp="^[A-Za-z]+$", message="Aceita só letras")
    private String name;

    @Min(value=18, message = "Tem que ser maior de idade")
    @Max(value = 150, message = "Digite uma idade valida")
    private int age;


    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }



}

The formulario.jsp shows the form page to register the person.

formulario.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

    <form action="adcionar" method="post" modelAttribute="person">
        Nome:<input type="text" name="name"/></br>
        Idade:<input type="number" name="age"/></br>
        <input type="submit" value="cadastrar"/>
    </form>

</body>
</html>

Once the registration is done, the system accesses the controller MainControl.java, where it checks whether the data on the person’s name and age is valid, if yes, it accesses a page to notify that the data on people has been saved, otherwise it goes back to the form page:

MainControl.java

package br.com.Test.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import br.com.Test.domain.Person;

@Controller
public class MainControl {

    @RequestMapping("/formulario")
    public ModelAndView formulario()
    {
        return new ModelAndView("pessoa/formulario");
    }

    @RequestMapping("/adcionar")
    public ModelAndView adcionar(@Valid Person p, BindingResult br) {
        System.out.println("oi");
        if(br.hasErrors()) {
            System.out.println("Error");
            return new ModelAndView("pessoa/formulario");
        }
        System.out.println(p.getName());
        System.out.println(p.getAge());
        ModelAndView mav = new ModelAndView("pessoa/adcionada");
        mav.addObject("pessoa",p);
        return mav;
    }

}

The problem: Binding result is registering invalid data.

Ex: Registered user without name (""), registered user with invalid name ("Luc45"), registered user under age(<18). In these cases the BindingResult.hasErrors() returns as false and allows approval of this data. The only case that BindingResult.hasErrors() returns as True, is when I register the person with the blank age field, it can detect the error, because it cannot register "" as age, because it is a String.

I wonder what’s missing for the BindingResult work together with validation, to recognise other invalidity?

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Test</groupId>
  <artifactId>Test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
    </plugins>
  </build>

<properties>
    <spring.version>5.2.0.RELEASE</spring.version>
</properties>

<dependencies>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>



<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.1.0.Alpha6</version>
</dependency>
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
   <groupId>org.glassfish.web</groupId>
   <artifactId>javax.el</artifactId>
   <version>2.2.4</version>
</dependency>
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>2.0.1.Final</version>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.5.2</version>
    <scope>test</scope>
</dependency>
</dependencies>
</project>

1 answer

0

I suggest making the Validator to be used for Spring:

1) Using XML

<mvc:annotation-driven />
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

2) Using @Configuration

@Configuration
public class ValidatorConfig {
    @Bean
    public javax.validation.Validator localValidatorFactoryBean() {
        return new LocalValidatorFactoryBean();
    }   
}

More details on documentation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.