Validate dates with Jquery validate for dd / mm / yyyy

1

I want to validate the dates with JQuery Validate, however, I researched a lot more the solutions found did not solve my problem.

My JS:

// incluir todos elementos do form na pagina
$("form").each(function () {
    // inicializa o plugin no each form
    $(this).validate({
        rules: {
            dataentrada: {
                dateBR: true
            },
            datavenc: {
                dateBR: true
            },
            dataproc: {
                dateBR: true

            }
        }
    });
}
);

//Valida Data PT-BR
jQuery.validator.addMethod("dateBR", function (value, element) {
    //contando chars
    if (value.length != 10)
        return this.optional(element) || false;
    // verificando data
    var data = value;
    var dia = data.substr(0, 2);
    var barra1 = data.substr(2, 1);
    var mes = data.substr(3, 2);
    var barra2 = data.substr(5, 1);
    var ano = data.substr(6, 4);
    if (data.length != 10 || barra1 != "/" || barra2 != "/" || isNaN(dia) || isNaN(mes) || isNaN(ano) || dia > 31 || mes > 12) {
        return this.optional(element) || false;
    }
    if ((mes == 4 || mes == 6 || mes == 9 || mes == 11) && dia == 31) {
        return this.optional(element) || false;
    }
    if (mes == 2 && (dia > 29 || (dia == 29 && ano % 4 !== 0))) {
        return this.optional(element) || false;
    }
    if (ano < 1900) {
        return this.optional(element) || false;
    }
    return this.optional(element) || true;
}, "Informe uma data válida"); /* Mensagem padrão */

When in the browser, the focus of the field is displayed, it shows an invalid date message.

    
asked by anonymous 28.09.2018 / 16:53

1 answer

1
  • Create a file named methods_pt.js with the following content.
  • Add the file where you call jquery (after)
  • See another way to do this: link

    jQuery.extend(jQuery.validator.methods, {
        date: function (value, element) {
            return this.optional(element) || /^\d\d?\/\d\d?\/\d\d\d?\d?$/.test(value);
        },
        number: function (value, element) {
            return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);
        }
    });
    
        
    04.10.2018 / 21:10