Validate a Form

Asked

Viewed 178 times

8

How do I display a alert() if the person has not completed a textarea, and a alert() that the comment was saved?

Javascript:

function saveTextAsFile() {

    var textToWrite = document.getElementById("inputTextToSave").value;

    var textFileAsBlob = new Blob([textToWrite], {
        type: 'text/plain'
    });

    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null) {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    } else {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);

    }

    downloadLink.click();
}

function destroyClickedElement(event) {
    document.body.removeChild(event.target);
}

function loadFileAsText() {
    var fileToLoad = document.getElementById("fileToLoad").files[0];

    var fileReader = new FileReader();

    fileReader.onload = function (fileLoadedEvent) {
        var textFromFileLoaded = fileLoadedEvent.target.result;
        document.getElementById("inputTextToSave").value = textFromFileLoaded;
    };

    fileReader.readAsText(fileToLoad, "UTF-8");
}

Obs: This script that is saving the comment in text document.

  • Your textarea id is inputTextToSave ?

3 answers

5


To solve your problem, I propose the following solution. To alert() empty textarea is very simple and remember that you need to validate the field with the file name too! And the process is the same below:

if(textToWrite == '') {
    alert('textarea vazia :´/');
    return;
}

As for the alert() from when the file was saved, it is already a little more complicated as we do not have a callback that is called after your file is downloaded. To solve this, I propose to use the setTimeout(). In it we set a timer to run a callback as in the example below:

setTimeout(function() {
  alert('arquivo baixado com sucesso!')
}, 2000);

Follows the jsfiddle.

3

Validation of fields

I suggest you create a function to validate the submission of the data to control the completion of the text field.

validationPreenchimento(Event);

In the onclick of your button or on onsubmit from your form assign the function validaPreenchimento(event);. It is also extremely important to check that the text is not just white space. Consider changing the function saveTextAsFile() for saveTextToFile(textContent, fileName) or change the function name, because what it does in fact is not only save text in file, it is save the text of a given field in file.

function validaPreenchimento(evt) {
    var textToWrite = document.getElementById("inputTextToSave").value;
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    // verificando tamanho da string ignorando espaços em branco nas extremidades (trim)
    if (textToWrite.replace(/^\s+|\s+$/gim, "").length == 0 ||
        fileNameToSaveAs.replace(/^\s+|\s+$/gim, "").length == 0) {
        alert("Os campos {texto} e {arquivo} são obrigatórios.");

        if (evt.preventDefault) {
            evt.preventDefault();
        }
        else {
            evt.returnValue = false; // IE
        }
    }
    else {
        saveTextAsFile();
    }
}

File recording

If the file is written synchronously simply put the alert at the end of the function saveTextAsFile(). Like the JavaScript is blocking I suggest using a setTimeout in the call of saveTextAsFile() to avoid screen locking while the file is written.

window.setTimeout(saveTextAsFile, 100);

2

In your saving method you can validate

function saveTextAsFile() {
  var textToWrite = document.getElementById("inputTextToSave").value;

  if ( textToWrite !== "" ){
      alert("Favor preencher todos campos");
      return;
  }
  var textFileAsBlob = new Blob([textToWrite], {
  type: 'text/plain'
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.