How to validate a form correctly?

Asked

Viewed 2,069 times

2

I’m studying Java EE, but I’m having a hard time validating data entry forms. My Search CadastrarInstrutor collects the form fields and checks their contents.

Below is the code of my JSP page (I put only the content of body of my page, and the validation form occurring in my.

cadastra-instructor.jsp

<%
    String erros = "";
    String converter = "";
    if (request.getAttribute("erro") != null && request.getAttribute("erroConverter") != null) {
        erros = (String) request.getAttribute("erro");
        converter = (String) request.getAttribute("erroConverter");
    }
%>

<form method="post" action="cadastroInstrutor">

    <p>Nome:
        <input type="text" name="nome"/>
        <span class="erro" style="color: red;">${erros}</span>
    </p>

    <p>Matrícula:
        <input type="text" name="matricula"/>
        <span class="erro" style="color: red;">${erros}</span>
    </p>

    <p>Conclusão de Gradução:
        <input type="text" name="graduacao"/>
        <span class="erro" style="color: red;">${erros}</span>
        <span class="erroConverter" style="color: red;">${erroConverter}</span>
    </p>

    <input type="submit" value="Enviar Dados"/>

</form>

Register instructor.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isFormValido = true;
    try {
        String nome = request.getParameter("nome");
        String matricula = request.getParameter("matricula");
        String ano = request.getParameter("graduacao");
        if (nome.isEmpty() || matricula.isEmpty() || ano.isEmpty()) {
            request.setAttribute("erro", "Você não preencheu todos os campos!\");
            isFormValido = false;
        }
        Integer anoGraduacao = Integer.parseInt(ano);
    } catch (NullPointerException e) {
        request.setAttribute("erro", "Você não preencheu todos os campos!");
        isFormValido = false;
    } catch (NumberFormatException e) {
        request.setAttribute("erroConverter", "Apenas números são aceitos neste campo!");
        isFormValido = false;
    }

    if (isFormValido) {
        // Salvar no banco e então redirecionar para a listagem.
        response.sendRedirect("listagem-instrutor.jsp");
    } else {
        request.getRequestDispatcher("cadastro-instrutor.jsp").forward(request, response);
    }
}

By definition of the teacher (will be introduced in the future), for now, the use of JSTL is unavailable, therefore the use of scriptlets. No Javascript focus for form validation.

The question then is: How would you perform this validation, and where would you perform it?

  • In Servlet I would check if the parameters are not null before using isEmpty. In the JSP, the {erros} I would leave only one at the beginning or end of the form and use the attribute required us inputs. I think only this to check if the form was filled in, if they were more complex validations I would create a specific Serublet for this.

1 answer

1


In using pure Servlet I would validate on the same screen, Html5 already provide this feature, also would do as you are doing but I would create a class for each object to validate its attributes. I mean, encapsulate the validations, you know,?

Here the Html5 working with validations: http://tableless.com.br/validacao-de-formularios-com-html5/

  • I ended up following this pattern. I created a validation class, where it validates each of the data, and when the errors occur, I add a message to a message list. If necessary, I could post my solution on this question to help anyone who might have such future problems with it.

Browser other questions tagged

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