Validate age JSF

0

When entering the age in a form using JSF I have to verify that the age is in a certain range and if not show an invalid date message. I had thought about using Java code that I had implemented from other years in a class that implements validator. The problem is that I do not know how to handle the parameter that is passed in the calculation method. I leave the code:

Form

<body>

    <ui:composition template="./WEB-INF/Template.xhtml">

        <ui:define name="content">
          <h:form>

              <f:event listener="#{registerView.validarPassword}" type="postValidate" />
              <p:panel header="Crear una nueva cuenta">
                  <h:panelGrid id="grid" columns="3">
                      <h:outputLabel for="name" value="Nombre:" style="font-weight:bold"/>
                      <p:inputText id="name" value="#{registerView.name}" required="true"
                                   requiredMessage="Introduzca su nombre." maxlength="30"/>
                      <p:message for="name"/>


                      <h:outputLabel for="apellidos" value="Apellidos:" style="font-weight:bold"/>
                      <p:inputText id="apellidos" value="#{registerView.apellidos}" required="true"
                                   requiredMessage="Introduzca sus apellidos." maxlength="30"/>
                      <p:message for="apellidos"/>

                      <h:outputLabel for="email" value="E-Mail:" style="font-weight:bold"/>
                      <p:inputText id="email" value="#{registerView.email}" required="true"
                                   requiredMessage="Introduzca su email.">
                         <f:validator validatorId="emailValidator" />
                      </p:inputText>

                      <p:message for="email"/>

                      <h:outputLabel for="fechanac" value="Fecha de nacimiento:" style="font-weight:bold"/>
                      <p:inputText type="Date" id="fechanac" value="#{registerView.fechanac}" required="true"
                                   requiredMessage="Introduzca su fecha de nacimiento.">

                      </p:inputText>

                      <p:message for="fechanac"/>

                        <h:outputLabel for="tarjeta" value="tarjeta de crédito:" style="font-weight:bold"/>
                      <p:inputText id="tarjeta" value="#{registerView.tarjeta}" required="true"
                                   requiredMessage="Introduzca su tarjeta de crédito." onkeypress="if (event.which &lt; 48 || event.which &gt; 57) return false;">
                        <f:convertNumber integerOnly="true"/>

                      </p:inputText>

                      <p:message for="tarjeta"/>

                        <h:outputLabel for="movil" value="Móvil(opcional):" style="font-weight:bold"/>
                      <p:inputText id="movil" value="#{registerView.movil}" required="false"/>




                      <p:message for="movil"/>



                      <h:outputLabel for="password" value="Contraseña:" style="font-weight:bold"/>
                      <p:password id="password" value="#{registerView.password}" feedback="true"
                                  required="true" requiredMessage="Introduzca su contraseña."
                                  validatorMessage="La contraseña debe contener al menos un número,
                                 así como caracteres tanto en mayúscula como en minúscula, además de 
                                 contar con una longitud comprendida entre 6 y 20 caracteres alfanuméricos">
                          <f:validateRegex pattern="((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})" />
                      </p:password>
                      <p:message for="password"/>
                      <h:outputLabel for="confirmpassword" value="Confirmar contraseña:" style="font-weight:bold"/>
                      <p:password id="confirmpassword" feedback="true"
                                  value="#{registerView.confirmPassword}" required="true"
                                  requiredMessage="Por favor, confirma tu contraseña."/>
                      <p:message for="confirmpassword"/>
                  </h:panelGrid>

                  <p:commandButton value="Registrarse" ajax="false" action="#{registerView.register}"/> 

              </p:panel>
          </h:form>

        </ui:define>

    </ui:composition>

</body>

Validator Java code

import java.text.SimpleDateFormat;

import java.util.Date;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.ValidatorException;

import javax.faces.validator.Validator;

@FacesValidator("agevalidator")
public class AgeValidator implements Validator {
public int GetAge(String fecha_nac) {     //fecha_nac debe tener el formato dd/MM/yyyy

Date fechaActual = new Date();
SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
String hoy = formato.format(fechaActual);
String[] date1 = fecha_nac.split("/");
String[] date2 = hoy.split("/");
int anios = Integer.parseInt(date2[2]) - Integer.parseInt(date1[2]);
int mes = Integer.parseInt(date2[1]) - Integer.parseInt(date1[1]);
if (mes < 0) {
  anios = anios - 1;
} else if (mes == 0) {
  int dia = Integer.parseInt(date2[0]) - Integer.parseInt(date1[0]);
  if (dia > 0) {
    anios = anios - 1;
  }
}
return anios;
}
 @Override
 public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    if (value == null) {
     return;
    }
}
}

Thanks in advance

    
asked by Iskandarina 16.05.2018 в 20:50
source

1 answer

0

When implementing Validator , the value entered by the user arrives in the value argument of the method signature. For the case that you raised the value entered you would get it like this:

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        //Fecha ingresada por el usuario
        String fechaDeNacimiento = String.class.cast(value); 
    }

Now, there is a certain contract to respect when we use a JSF Validator and that, in case the validation does not pass, an exception of type ValidatorException should be thrown.

On the other hand, I do not understand your business rule to validate the date of birth. The treatment you are doing is somewhat complex. I think it would be easier for you to use a Converter to define how to transform plain text to a date type object when POST is done. That way, you could use a more object-oriented validation using Joda Time or (which is the same thing) the api of Java 8 dates. I'll show you this example to see if it clears up a bit what I say:

I want to validate that the user is not under age (suppose that the age of majority is 18 years old)

    <div class="ui-g">
        <div class="ui-g-12">
            <p:outputLabel value="Ingrese la fecha de nacimiento (dd/MM/yyyy)" for="fechaNacimiento"/>
            <p:inputText id="fechaNacimiento"
                value="#{controladorFechaNacimiento.fechaNacimiento}"
                converter="jodaLocalDateConverter"
                validator="validadorFechaNacimiento"/>
        </div>
    </div>

If you notice, the component will pass two attributes: converter and validator.

JodaLocalDateConverter: It is responsible for representing the object as text when drawing the html, and for converting the text to the object when the post is made:

    @FacesConverter("jodaLocalDateConverter")
    public class JodaLocalDateConverter implements Converter { 

        private DateTimeFormatter formatter = 
        DateTimeFormat.forPattern("dd/MM/yyyy");    
        @Override
        public Object getAsObject(FacesContext context, UIComponent component, 
            String value) {

            return formatter.parseDateTime(value).toLocalDate();
        }

        @Override
        public String getAsString(FacesContext context, UIComponent 
        component, Object value) {

            return formatter.print((LocalDate) value);
       }
    }

And finally the validator of date of birth:

    @FacesValidator("validadorFechaNacimiento")
    public class ValidadorFechaNacimiento implements Validator {

        private static final int EDAD_MINIMA_PERMITIDA = 18;

        @Override
        public void validate(FacesContext facesContext, UIComponent 
        componente, Object valor) throws ValidatorException {

            //El objeto valor es de tipo LocalDate porque el converter JodaLocalDateConverter
            //invoco al metodo getAsObject
            LocalDate fechaNacimiento = new LocalDate(valor);        
            Years anios = Years.yearsBetween(fechaNacimiento, 
            LocalDate.now());

            if (anios.getYears() < EDAD_MINIMA_PERMITIDA) {

                FacesMessage facesMessage = new FacesMessage("Edad no 
                             permitida", "Debes tener más de " + EDAD_MINIMA_PERMITIDA + " para ingresar");
                facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(facesMessage);
            }        
        }
    }

I extended a bit but I hope it will be useful to you

    
answered by 24.05.2018 / 05:59
source