javascript Publicado por: 5

Con esta clase javascript, la validación de fechas y/o horas será pan comido.

Se controla si la fecha es en formato europeo o de estados unidos. Controla el número de días que tiene casa mes, e incluso controla el número de dias del mes de febrero, según si el año es bisiesto o no.

Aquí teneis el fichero para descargar: date_validator

Y aquí os dejamos el código completo:

function DateValidator() {

    /* Funcion para calcular la validez de una fecha */
    this.chkdate = function (objName,sValue) {
        var strDatestyle = "eu";
        var strDate;
        var strDateArray;
        var strDay;
        var strMonth;
        var strYear;
        var intday;
        var intMonth;
        var intYear;
        var booFound = false;
        var datefield = objName;
        var strSeparatorArray = new Array("-"," ","/",".");
        var intElementNr;
        var err = 0;
        var strMonthArray = new Array(12);

        strMonthArray[0] = "/01/";
        strMonthArray[1] = "/2/";
        strMonthArray[2] = "/3/";
        strMonthArray[3] = "/4/";
        strMonthArray[4] = "/5/";
        strMonthArray[5] = "/6/";
        strMonthArray[6] = "/7/";
        strMonthArray[7] = "/8/";
        strMonthArray[8] = "/9/";
        strMonthArray[9] = "/10/";
        strMonthArray[10] = "/11/";
        strMonthArray[11] = "/12/";

        if (datefield!=null) {
            strDate = datefield.value;
        }

        if (sValue!= null) {
            strDate = sValue;
        }    

        if (strDate.length < 6) {
            return false;
        }

        for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
            if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
                strDateArray = strDate.split(strSeparatorArray[intElementNr]);
                if (strDateArray.length != 3) {
                    err = 1;
                    return false;
                }
                else {
                    strDay = strDateArray[0];
                    strMonth = strDateArray[1];
                    strYear = strDateArray[2];
                }
                booFound = true;
            }
        }

        if (booFound == false) {
            if (strDate.length>5) {
                strDay = strDate.substr(0, 2);
                strMonth = strDate.substr(2, 2);
                strYear = strDate.substr(4);
            }
        }

        if (strYear.length == 2) {
            strYear = '20' + strYear;
        }

        // US style
        if (strDatestyle == "US") {
            strTemp = strDay;
            strDay = strMonth;
            strMonth = strTemp;
        }

        intday = parseInt(strDay, 10);
        if (isNaN(intday)) {
            err = 2;
            return false;
        }

        intMonth = parseInt(strMonth, 10);
        if (isNaN(intMonth)) {
            for (i = 0;i<12;i++) {
                if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
                    intMonth = i+1;
                    strMonth = strMonthArray[i];
                    i = 12;
                }
            }
            if (isNaN(intMonth)) {
                err = 3;
                return false;
            }
        }

        intYear = parseInt(strYear, 10);
        if (isNaN(intYear)) {
            err = 4;
            return false;
        }

        if (intMonth>12 || intMonth<1) {
            err = 5;
            return false;
        }

        if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
            err = 6;
            return false;
        }

        if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
            err = 7;
            return false;
        }

        if (intMonth == 2) {
            if (intday < 1) {
                err = 8;
                return false;
            }
            if (this.LeapYear(intYear) == true) {
                if (intday > 29) {
                    err = 9;
                    return false;
                }
            }
            else {
                if (intday > 28) {
                    err = 10;
                    return false;
                }
            }
        }

        return true;
    }

    /* Año bisiesto */
    this.LeapYear = function (intYear) {
        if (intYear % 100 == 0) {
            if (intYear % 400 == 0) { return true; }
        }
        else {
            if ((intYear % 4) == 0) { return true; }
        }
        return false;
    }

    /* Formato de hora */
    this.chkHora = function (lahora) {
        var arrHora = (lahora.value).split(":");
        if (arrHora.length!=2) {
            return false;
        }
        if (parseInt(arrHora[0])<0 || parseInt(arrHora[0])>23) {
            return false;
        }

        if (parseInt(arrHora[1])<0 || parseInt(arrHora[1])>59) {
            return false;
        }
        return true;
    }

}

5 Comentarios

  1. santiago

    gracias, no soy muy bueno en javs, apenas aprendiendo, pero como llamo a las funciones con los valores a pasar, por ejemplo si el usuario introduce la hora yo la recibo con mi variable llamada var hora=20:55, por ejemplo.
    entonces como la paso a la funcion que tienes?

    gracias

    1. Administrador Microteching Autor del artículo

      Hola Santiago,
      Te paso un ejemplo de como podrías validar ese ‘hora’:

      var dv = new DateValidator();
      var result = dv.chkHora(null, hora);

      También seria posible validar un campo con una fecha con algo como:
      var dv = new DateValidator();
      var result = dv.chkdate(document.getElementById(‘ID_DE_TU_CAMPO_FECHA’), null);

      Creo que debe ser algo así aunque no lo estoy comprobando ahora mismo. Puede que tenga algún fallo de sintaxis.

      Saludos!

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.