Clear Field with JavaScript

4

I'm using this function below, to validate the date in all date type fields of the form, I call the function in the onBlur event of the txt.

 function VerificaData(digData) {
            var bissexto = 0;
            var data = digData;
            var tam = data.length;
            if (tam == 10)
            {
                var dia = data.substr(0, 2);
                var mes = data.substr(3, 2);
                var ano = data.substr(6, 4);
                if ((ano > 1900) || (ano < 2100)) {
                    switch (mes)
                    {
                        case '01':
                        case '03':
                        case '05':
                        case '07':
                        case '08':
                        case '10':
                        case '12':
                            if (dia <= 31)
                            { return true; }
                            break;
                        case '04':
                        case '06':
                        case '09':
                        case '11':
                            if (dia <= 30)
                            { return true; }
                            break;
                        case '02':
                            if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0))
                            { bissexto = 1; }
                            if ((bissexto == 1) && (dia <= 29))
                            { return true; }
                            if ((bissexto != 1) && (dia <= 28))
                            { return true; }
                            break;
                    }
                }
            }
            alert("A Data " + data + " é inválida!");
            
            return false;
        }

But I would like to know how do I make the date when the date is invalid, clear the field? I tried to form it would work, if it was a txt and a function, but I use this function for several txts, so the forms I tried and researched do not work. So I call the function:

onBlur="VerificaData(this.value);
    
asked by anonymous 11.08.2017 / 22:52

3 answers

5

You can construct another function that interprets the result of the date verification and clears it if it does not receive true :

function limparDataInvalida(campo){
     if (!VerificaData(campo.value)){
          campo.value = '';
     }
}

And the onblur is running out of .value , like this:

<input ... onblur="limparDataInvalida(this);">

Edit

To avoid the infinite looping of loops due to the fact that alert within VerificaData call onblur can:

  • Display the message in a way other than alert , for example with a Jquery UI Dialog message.

Or

  • Do not validate the date if it has already been cleaned and therefore is empty, modifying if to look like this:

    function limparDataInvalida(campo){
        //agora aqui vê primeiro se não é vazio
        if (campo.value != '' && !VerificaData(campo.value)){
            campo.value = '';
            campo.focus();
        }
    }
    
11.08.2017 / 23:01
3

Even though the response was given by @Isac, I wanted to leave my contribution here.

You can use a completely JavaScript solution, without having to pass anything to HTML. Particularly because I like to keep everything separate (HTML, CSS, JS, PHP, Python, Java, etc.).

You can add a event listener to document to monitor the blur of the type data type or class that contains the date values, then perform its function.

Knowing the Document Object Model is a great way to not get lost. Study it! You will not regret it.

EDITION

Using only JavaScript

First method, no prototype :

// Seleciona os input tipo datanuma NodeList
var inputTipoData = document.querySelectorAll('input[type="date"]'),
    // Seleciona os input com a classe .date numa NOdeList
    inputClasseData = document.getElementsByClassName('date');

// Aplica o addEventListener para os input com tipo date
for (var i = 0; i < inputTipoData.length; i++) {
    inputTipoData[i].addEventListener('click', alertaOnBlur);
}

// Aplica o addEventListener para os input com classe date
for (var i = 0; i < inputClasseData.length; i++) {
    inputClasseData[i].addEventListener('blur', alertaOnBlur);
}
// Declara a função que será executada
function alertaOnBlur () {
    alert("Blur!!!");
};

Second method, with prototype :

// Cria um protótipo para iterar uma NodeList monitorando cada elemento com 
// addEventListener
NodeList.prototype.addEventListener = function(event, func) {
    this.forEach(function(content, item) {
       content.addEventListener(event, func);
    });
}

// Função definida por mim
function minhaFuncao () {
    alert("AAAHHHHHHH!!!");
}

// Pega todos os formulário tipo date na página
var formularioDate = document.querySelectorAll("input[type='date']");

// Monitora todos os formulários da lista acima com addEventListener
formularioDate.addEventListener("blur", minhaFuncao);
    
11.08.2017 / 23:19
2

You can also, instead of creating a new function, in the same function VerificaData(digData) add the code below after alert :

window.focus();
campos = document.getElementsByTagName("input");
for (var x=0; x < campos.length; x++) {
  if(campos[x].value == digData) {
    campos[x].value = "";
  }

}

This code will check the field with value sent in digData and empty it.

The window.focus(); is to take the focus() of the field to prevent alert from being infinite.

Your code looks like this:

function VerificaData(digData) {
            var bissexto = 0;
            var data = digData;
            var tam = data.length;
            if (tam == 10)
            {
                var dia = data.substr(0, 2);
                var mes = data.substr(3, 2);
                var ano = data.substr(6, 4);
                if ((ano > 1900) || (ano < 2100)) {
                    switch (mes)
                    {
                        case '01':
                        case '03':
                        case '05':
                        case '07':
                        case '08':
                        case '10':
                        case '12':
                            if (dia <= 31)
                            { return true; }
                            break;
                        case '04':
                        case '06':
                        case '09':
                        case '11':
                            if (dia <= 30)
                            { return true; }
                            break;
                        case '02':
                            if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0))
                            { bissexto = 1; }
                            if ((bissexto == 1) && (dia <= 29))
                            { return true; }
                            if ((bissexto != 1) && (dia <= 28))
                            { return true; }
                            break;
                    }
                }
            }

            alert("A Data " + data + " é inválida!");
            window.focus();

            campos = document.getElementsByTagName("input");
            for (var x=0; x < campos.length; x++) {
                if(campos[x].value == digData) {
                    campos[x].value = "";
                }
            }            
            return false;
        }
    
12.08.2017 / 05:16