Do not let date include 50 years back in the database

2

I have a JSF and PrimeFaces 4.0 system and I have a <p: calendar> field in which I made the treatment not to load dates in the current day's calendar up to -50 years old.

But even so, the user can type it through the keyboard and insert it into the database.

I need a method to not include such a date, what would be the best way to do it?

Here is an example of the class:

public class DocumentoClienteModel  {

    private Date dateInicio;

    public Date getDtInicio() {
        return dtInicio;
    }

    public void setDtInicio(final Date dtInicio) {
        this.dtInicio = dtInicio;
    }
}
    
asked by anonymous 25.10.2018 / 16:01

1 answer

1

I would make a method to get the minimum date and set the component, thus:

public Date getMinDate(){
    Date minDate = new Date();
    Calendar calendarData = Calendar.getInstance();
    calendarData.setTime(minDate);
    calendarData.add(Calendar.YEAR,-50);

    return calendarData.getTime();
}

no xhtml:

    <h:form>
        <p:calendar value="#{mBDates.minhaData}"  mindate="#{mBDates.minDate}" id="dtLast"></p:calendar>
        <p:message for="dtLast" display="icon" />
    </h:form>

And in case the clever user type the date on the hand, he would put a validation before saving:

public boolean dataValida(Date data){
    int compare = data.compareTo(getMinDate());
    //se a data for igual ou menor a data minima retorna falso
    //e não salva meu formulario, lançando uma advertencia para o usuário
    if(compare == 0 || compare == -1)
        return false;
    //senão retorna que a data é valida e salva meu formuladrio
    return true;
}



    public void salvarMeuForm(){
        if(!dataValida(minhaEntidade.getMinhaData()))
           FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro!", "Data não permitida."));
   }
    
25.10.2018 / 21:05