Validate a date received from html5 Date in java and send it to Mysql

0

I have this code that works very well, it receives input parameters from a DOM and sends them through ajax to an endpoint that sends them to the DB at the same time. the theme comes here, I want to validate two dates, one for planes and one for arrival, however the parameters that are in the setString () are clearly String, which I do not think I can validate them.

I put those input as String since the input html5 gives me a format type String "yyyy-MM-dd", which is the same format that the Date column of Mysql receives. (The insert works very well but now I want to validate) How can I build that String that I receive from an HTML and be able to validate it beforehand to the database?

My idea is to do a static class, however I am overwhelmed by the amount of classes related to the dates that I have and I do not know how to do it, one fact is that I am using java 8 and several methods of the Date class do not allows them to use "deprecated".

I leave parts of code.

endpoint:

                        PreparedStatement ps;
                        String sql="INSERT INTO vuelos(id_avion, id_administrador, empresa, destino, escalas, pasajes, fechaSalida, horarioSalida, fechaArribo, horarioArribo, pago, precio) values(?,?,?,?,?,?,?,?,?,?,?,?)";
                        ps= con.prepareStatement(sql);

                        ps.setInt(1, id_avion);
                        ps.setInt(2, int_id_usuarioAdmin);
                        ps.setString(3, empresa);
                        ps.setString(4, destino);
                        ps.setInt(5, escalas);
                        ps.setInt(6, pasajes);
                        ps.setString(7, fechaSalida); //validar
                        ps.setString(8, horarioSalida);//validar
                        ps.setString(9, fechaArribo);
                        ps.setString(10, horarioArribo);
                        ps.setString(11, pago);
                        ps.setInt(12, precio);

                        ps.executeUpdate();
                        ps.close();

                        listado.add(new Vuelo(0,empresa,destino, escalas, pasajes, fechaSalida, horarioSalida,fechaArribo, horarioArribo, pago, precio));

                        str_toJson= gson.toJson(listado);
                        return str_toJson;

                        }

Part of the html:     

<tr>
    <td>
        <input id="fechaSalida" type="date">
    </td>

    <td>
        <input id="horarioSalida" type="time" name="horarioSalida">
    </td>
</tr>

<tr>
    <td>
        <label name="fechaArribo">Fecha de arribo:</label>
    </td>

    <td>
        <label name="HorarioArribo">Horario de arribo:</label>
    </td>
</tr>

<tr>
    <td>
        <input id="fechaArribo" type="date">
    </td>

    <td>
        <input id="horarioArribo" type="time" name="horarioArribo">
    </td>
</tr>
    
asked by berlot83 13.04.2017 в 17:04
source

3 answers

1

Before preparing the Query sql you must do the following:

import java.text.SimpleDateFormat 

....

​SimpleDateFormat validador = new SimpleDateFormat("yyyy-MM-dd")
Date fechaSalidaValida = format.parse("2017-04-12")
​​​​​​​​​​​Date fechaEntradaValida = format.parse("2017-03-01")

If any of the two dates is not valid, an exception will be thrown, which you must use in the method that calls the code you presented.

    
answered by 13.04.2017 / 17:39
source
2

Good morning

Since you do not have any web-level control of what you can enter, simple solutions such as SimpleDateFormat may be insufficient.

Simple solution (but with error cases)

I think what you're asking is something like this (adapt the SimpleDateFormat to your liking). With what you have in date, you should be able to work without problems.

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy",     Locale.UK);
sdf.setLenient(false); // Importante para que valide, sino fechas como 33/01/2017 te las devolvería como su fecha correspondiente en Febrero.
Date date=null;
  try {
 date = sdf.parse("Mon Mar 14 16:02:37 GMT 2011");
    } catch (ParseException ex) {
        System.out.println("Fecha no valida o fuera de formato");
    }

By location issues, the ideal is to pass the date in their numerical values, therefore, you could call the SimpleDateFormat without the locale.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 

The problem lies in that for example, even with setLenient (false) data entries like 2017-02-3x I would give them as valid.

Other solutions

I suggest you take a look at the two alternatives proposed in this link link

The solution with JodaTime seems the easiest way to achieve what you want with a more solid validation.

Greetings

    
answered by 13.04.2017 в 17:21
1

You can define this class in the same servlet below if it complicates you then import it

public class parsearDate(dateInString){    
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");

    try {
        Date date = formatter.parse(dateInString);
        return date;
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

This method should be called before settear.

ps.setString(7, fechaSalida);

The idea is that you validate all the fields before starting to create the instance of the class object, so that once everything is validated, then there it starts to set.

I leave an example so you can use it to validate:

Ex:

try {
    Date date = parsearDate(fechaSalida);
    // hacer todas las validaciones

    //Comienza setteo
} catch (ParseException e) {
    e.printStackTrace(); 
    //Devolver error por que se genero un error al validar o settear
}

I hope this helps you: D

    
answered by 13.04.2017 в 17:22