Exceptions order to validate java date

1

I would like to validate a date with the format MM / DD / AA, through a program, to which this date is passed as a parameter, divide it through StringTokenizer into elements, and take into account the exceptions producing an error when it is a non-numeric element, if it was not introduced, or if an impossible date is specified.

I find a problem when I create the new exception and try to join the RuntimeException for empty elements or that are not numeric, I would like to know the best way to put them together and organize them correctly.

Thank you.

public class ValidaFecha {


    public class fechaNoValida extends Exception{
        public fechaNoValida(){ }
        public fechaNoValida(String cadena){
                 super(cadena); //Llama al constructor de Exception y le pasa el contenido de cadena
        }
    }

    public void validarFecha(String fecha) throws fechaNoValida{

        StringTokenizer tokens = new StringTokenizer(fecha,"/");

    while(tokens.hasMoreTokens()){

//            if(tokens.nextToken() == null || tokens.nextToken().isEmpty()){
//                throw new RuntimeException("Has introducido un valor nulo.");
//            }

            if(Integer.parseInt(tokens.nextToken()) <= 0){
                throw new fechaNoValida("Has introducido algún elemento negativo.");
            }

        }
    }

    public void mostrarFecha(String fecha) throws fechaNoValida{
        validarFecha(fecha);
        StringTokenizer tokens=new StringTokenizer(fecha,"/");
    while(tokens.hasMoreTokens()){

            System.out.println(tokens.nextToken());

        }

    }


    public static void main(String[] args) {
        ValidaFecha prueba = new ValidaFecha();
        try{
            prueba.mostrarFecha("11/12/12");
        }catch(fechaNoValida e){
            System.out.println(e.getMessage());
        }catch(RuntimeException ex){
            System.out.println(ex.getMessage());
        }

    }

}
    
asked by Nando 02.10.2016 в 21:52
source

2 answers

0

Validate a date is more than validate the format, you also have to take into account that the number of days corresponds to the month number, in the previous example if it will validate the date 99/99/123 which does not correspond with the format DD / MM / YY, you can expand the previous version:

public void validarFecha(String fecha) throws fechaNoValida{

    StringTokenizer tokens = new StringTokenizer(fecha,"/");
    int pos = 0;
    int dia = 0;
    int mes = 0;
   while(tokens.hasMoreTokens()){
        /* Capturamos el Token para Validar */
        String token = tokens.nextToken();

        if(token == null || token.trim().length()<=0){
            throw new fechaNoValida("Has introducido un valor nulo o vacío.");
        }
        else
        {
          /*Caracter no númerico */
          if(Character.isLetter(token.charAt(0))){
                throw new fechaNoValida("Caracter " + token+  " no Númerico ");
          }
          else if (Integer.parseInt(token) <= 0){
              throw new fechaNoValida("Has introducido algún elemento negativo o cero.");
          }
          else if (pos > 2){
              throw new fechaNoValida("La fecha no corresponde al formato DD/MM/YY");
          }
          else if (pos == 0){
              //Validando el DD no puede ser mayor de 31
              dia = Integer.parseInt(token);
              if (dia > 31)
                throw new fechaNoValida("DD incorrecto");
          }
           else if (pos == 1){          
              //Validando el MM no puede ser mayor de 12
              mes = Integer.parseInt(token);
              if (mes > 12) {
                throw new fechaNoValida("MM incorrecto");
              }
              else {
                //Validando el día en función del mes, solo comprobamos los meses con menos de 31 dias
                switch mes{                 
                    case 2: // 29 dias
                        if (dia > 29)
                            throw new fechaNoValida("El día no corresponde al mes de febrero");
                        break;

                    case 4: // 30 dias
                    case 6: // 30 dias
                    case 9: // 30 dias
                    case 11: // 30 dias
                        if (dia > 30)
                            throw new fechaNoValida("El día no corresponde al mes " + mes);
                        break;

                }
              }
          }
          else if (pos == 2){
              //Validando el MM no puede ser mayor de 99
              if (Integer.parseInt(token) > 100)
                throw new fechaNoValida("YY incorrecto");
          }
          pos = pos + 1;
        }
        /* Imprimir el Token*/
        System.out.println(token);
    }
}
    
answered by 17.10.2016 / 17:42
source
2

Some recommendations for your code:

  • The mostrarFecha() method does the same thing as validarFecha() could compress its logic in a single method
  • Store the token in a variable to perform the corresponding validation, because the nextToken() returns the next token (even if it sounds redundant) so if you enter A/12/1212 your validation if (commented) would do the following

    if(tokens.nextToken() == null || tokens.nextToken().isEmpty())
     /* asignando valores haría la siguiente validación*/
    if(A == null || 12.isEmpty())
    

Then your compressed method could be like this (Modifiable to take into account some validations but that I leave to your imagination):

 public void validarFecha(String fecha) throws fechaNoValida{

    StringTokenizer tokens = new StringTokenizer(fecha,"/");
   while(tokens.hasMoreTokens()){
        /* Capturamos el Token para Validar */
        String token = tokens.nextToken();
        if(token == null || token.trim().length()<=0){
            throw new fechaNoValida("Has introducido un valor nulo o vacío.");
        }
        else
        {
          /*Caracter no númerico */
          if(Character.isLetter(token.charAt(0))){
                throw new fechaNoValida("Caracter " + token+  " no Númerico ");
           }
          else if (Integer.parseInt(token) <= 0){
              throw new fechaNoValida("Has introducido algún elemento negativo o cero.");
          }
        }
        /* Imprimir el Token*/
        System.out.println(token);
    }
}
    
answered by 03.10.2016 в 04:26