Error in field validation

Asked

Viewed 309 times

1

I have the following class:

package br.com.pokemax.modelo;

import java.util.Collection;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotBlank;

@Entity
@Table(name = "geracao")
public class Geracao {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Nome não pode estar em branco.")
    @Pattern(regexp = "[A-z]*", message = "Atenção, digite somente letras")
    @Size(max = 20, message = "Máximo de 20 caracteres permitidos.")
    @Column(length = 20, nullable = false)
    private String nome;

    @NotBlank
    @Pattern(regexp = "[0-9]*", message = "Atenção, digite somente números")
    private Integer numero;

    @OneToMany(mappedBy = "geracao", fetch = FetchType.LAZY)
    private Collection<Habilidade> habilidades;

    public Geracao() {

    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Integer getNumero() {
        return numero;
    }

    public void setNumero(Integer numero) {
        this.numero = numero;
    }

    public Collection<Habilidade> getHabilidades() {
        return habilidades;
    }

    public void setHabilidades(Collection<Habilidade> habilidades) {
        this.habilidades = habilidades;
    }

}

My xhtml page:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">
<ui:composition template="/layout/template.xhtml">
    <ui:define name="content">

        <h:form id="pesquisa" rendered="#{geracaomb.geracao == null}">
            <p:panel header="#{msg['geracao']}">
                <p:messages id="messages" showDetail="true" autoUpdate="true"
                    closable="true" />
                <h:panelGrid id="camposPesquisa" columns="2">
                    <h:outputLabel value="#{msg['nome']}: " />
                    <p:inputText value="#{geracaomb.arg}" />
                </h:panelGrid>
                <h:panelGrid id="botoes" columns="2" styleClass="botoesCrud">
                    <p:commandButton actionListener="#{geracaomb.pesquisar}"
                        value="#{msg['pesquisar']}" ajax="false"
                        update="cadastro,pesquisa" />
                    <p:commandButton actionListener="#{geracaomb.novo}"
                        value="#{msg['novo']}" ajax="false" update="cadastro"
                        styleClass="separadorBotoes" />
                </h:panelGrid>

                <p:dataTable id="tabela" var="linha" value="#{geracaomb.lista}"
                    paginator="true" rows="10" rendered="#{not empty geracaomb.lista}" paginatorPosition="top">
                    <p:column styleClass="botoesGrid">
                        <p:commandButton icon="ui-icon-pencil"
                            action="#{geracaomb.editar(linha.id)}" process="@this"
                            update="cadastro,pesquisa" ajax="false" />
                        <p:commandButton icon="ui-icon-trash"
                            action="#{geracaomb.excluir(linha)}" ajax="true" process="@this">
                            <p:confirm header="#{msg['cabecalho.apagar.registro']}"
                                message="#{msg['apagar.registro']}" icon="ui-icon-alert" />
                        </p:commandButton>
                        <p:confirmDialog global="true" showEffect="exploud"
                            hideEffect="fade">
                            <p:commandButton value="Sim" type="button"
                                styleClass="ui-confirmdialog-yes" icon="ui-icon-check" />
                            <p:commandButton value="Não" type="button"
                                styleClass="ui-confirmdialog-no" icon="ui-icon-close" />
                        </p:confirmDialog>
                    </p:column>
                    <p:column headerText="#{msg['nome']}" sortBy="#{linha.nome}"
                        style="width:12%;">
                        <h:outputText value="#{linha.nome}" />
                    </p:column>
                    <p:column headerText="#{msg['efeito']}" sortBy="#{linha.numero}">
                        <h:outputText value="#{linha.numero}" />
                    </p:column>
                </p:dataTable>
            </p:panel>
        </h:form>

        <h:form id="cadastro" rendered="#{geracaomb.geracao != null}">
            <p:messages id="messages" showDetail="true" autoUpdate="true"
                closable="true" />
            <p:panel>
                <f:facet name="header">
                    <h:outputText
                        value="#{geracaomb.geracao.id == null ? msg['cadastrando.geracao'] : msg['atualizando.geracao']}" />
                </f:facet>
                <h:panelGrid id="informacoesCadastro" columns="3">
                    <h:outputLabel value="#{msg['nome']}" />
                    <p:inputText id="nome" value="#{geracaomb.geracao.nome}" size="20" />
                    <p:message for="nome" />
                    <h:outputLabel value="#{msg['numero']} " rendered="true" />
                    <p:inputText id="numero" value="#{geracaomb.geracao.numero}" />
                    <p:message for="numero" />
                </h:panelGrid>
                <h:panelGrid columns="3" styleClass="botoesCrud">
                    <p:commandButton action="#{geracaomb.gravar}"
                        value="#{msg['salvar']}" update="cadastro" />
                    <p:commandButton action="#{geracaomb.cancelar}"
                        value="#{msg['cancelar']}"
                        update="cadastro,pesquisa,:pesquisa:tabela" immediate="true"
                        ajax="false" styleClass="separadorBotoes" />
                    <p:commandButton actionListener="#{geracaomb.novo}"
                        value="#{msg['novo']}" ajax="false"
                        rendered="#{geracaomb.geracao.id != null}"
                        styleClass="separadorBotoes" />
                </h:panelGrid>
            </p:panel>
        </h:form>

    </ui:define>
</ui:composition>
</html>

And my method record:

public void gravar() {
        try {
            if (geracao.getId() == null) {
                dao.insert(geracao);
                MensagensUtil.sucesso("Geração " + geracao.getNome() + " cadastrado(a) com sucesso!");
                geracao = new Geracao();
            } else {
                dao.update(geracao);
                MensagensUtil.sucesso("Geração " + geracao.getNome() + " atualizado(a) com sucesso!");
                // lista = dao.findByName(arg);
            }

        } catch (Exception e) {
            MensagensUtil.erro(e.getMessage());
            return;
        }

    }

When I try to make a new registration nothing happens on the screen and in my log I have the following error message:

17:52:52,620 SEVERE [javax.enterprise.Resource.webcontainer.jsf.context] (default task-4) javax.validation.Unexpectedtypeexception: HV000030: No Validator could be found for Constraint 'javax.validation.constraints.Pattern' validating type 'java.lang.Integer'. Check Configuration for 'numero' at org.hibernate.Validator.internal.engine.constrainaintvalidation.Constrainttree.throwExceptionForNullValidator(Constrainttree.java:229) at org.hibernate.Validator.internal.engine.constrainaintvalidation.Constrainttree.getConstraintValidatorNoUnwrapping(Constrainttree.java:310) at org.hibernate.Validator.internal.engine.constrainaintvalidation.Constrainttree.getConstraintValidatorInstanceForAutomaticUnwrapping(Constrainttree.java:244) at org.hibernate.Validator.internal.engine.constrainaintvalidation.Constrainttree.getInitializedConstraintValidator(Constrainttree.java:163) at org.hibernate.Validator.internal.engine.constrainaintvalidation.Constrainttree.validateConstraints(Constrainttree.java:116) at org.hibernate.Validator.internal.engine.constrainaintvalidation.Constrainttree.validateConstraints(Constrainttree.java:87) at org.hibernate.Validator.internal.Metadata.core.Metaconstraint.validateConstraint(Metaconstraint.java:73) at org.hibernate.Validator.internal.engine.ValidatorImpl.validateMetaConstraint(Validatorimpl.java:617) at org.hibernate.Validator.internal.engine.ValidatorImpl.validateConstraint(Validatorimpl.java:580) at org.hibernate.Validator.internal.engine.ValidatorImpl.validatePropertyForSingleDefaultGroupElement(Validatorimpl.java:1074) at org.hibernate.Validator.internal.engine.ValidatorImpl.validatePropertyForDefaultGroup(Validatorimpl.java:1042) at org.hibernate.Validator.internal.engine.ValidatorImpl.validatePropertyForCurrentGroup(Validatorimpl.java:957) at org.hibernate.Validator.internal.engine.ValidatorImpl.validateValueInContext(Validatorimpl.java:905) at org.hibernate.Validator.internal.engine.ValidatorImpl.validateValue(Validatorimpl.java:239) at javax.faces.Validator.BeanValidator.validate(Beanvalidator.java:316) at javax.faces.Component.UIInput.validateValue(Uiinput.java:1164) at javax.faces.Component.UIInput.validate(Uiinput.java:982) at javax.faces.Component.UIInput.executeValidate(Uiinput.java:1248) at javax.faces.Component.UIInput.processValidators(Uiinput.java:712) at javax.faces.Component.UIComponentBase.processValidators(Uicomponentbase.java:1261) at javax.faces.Component.UIComponentBase.processValidators(Uicomponentbase.java:1261) at org.primefaces.Component.panel.Panel.processValidators(Panel.java:299) at javax.faces.Component.UIForm.processValidators(Uiform.java:253) at javax.faces.Component.UIComponentBase.processValidators(Uicomponentbase.java:1261))

Someone knows where my mistake is and can help me please?

  • See this: http://meta.pt.stackoverflow.com/q/5359/132

1 answer

1


Your mistake is simple. See in your entity:

@Pattern(regexp = "[0-9]*", message = "Atenção, digite somente números")
private Integer numero;

The annotation @Pattern shall not be used in fields of type Integer. The reason is because it doesn’t make sense. There’s no such thing as yours Integer have anything other than a number that can trigger your validation message.

Therefore, the solution would be one of the following:

  • Take out the annotation @Pattern. If you want, use the notes @Max and/or @Min to delimit the desired numbers, such as this example:

    @Min(value = 1, message = "Atenção, digite somente números de 1 a 721")
    @Max(value = 721, message = "Atenção, digite somente números de 1 a 721")
    private Integer numero;
    
  • Change the field type as well as the getter and Setter to String.

In addition, the annotation @NotBlank also cannot be used in fields of type Integer. So if you prefer the first option, remove it as well.

  • I discovered this by giving a researched further sinking, but it was just that. Thank you very much.

Browser other questions tagged

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