How to validate an upload by file name?

Asked

Viewed 156 times

0

I am trying to validate the upload of a file , and the same should always be called new.mpg, if not, the program will not work.

function validarNomeArquivo(){
    //variavel que recebe o nome do arquivo
    var  oImg = "bgs/newFile.mpg";
    //variavel para comparar o input 
        var x = document.getElementById('fileBgAtualHD').value;;
                if(x==oImg){
                alert("yes");
                alert(x + " x yes ");
                alert(oImg + "  oImg yes ");
                    return true;
            }
                else{
                    alert("no");
                    alert(x + "  x no");
                    alert(oImg + "  oImg no ");
                    return false;
                }
        }

2 answers

0


The problem is that when attaching some file, the Javascript also creates a path, then the value of the element is more or less like this: C:\fakepath\nome-do-arquivo.jpg.

For this reason the condition will always be false in your code.

Try to leave your function like this:

function validarNomeArquivo() {
    var oImg = 'new.mpg';
    var x = document.getElementById('fileBgAtualHD').value;

    x = x.split('\\');
    x = x[x.length - 1];

    if (x == oImg) {
        return true;
    } else {
        return false;
    }
}
  • It worked man ! Thanks , ball show :)

  • Needing we are there! D

0

You can use the property name of file object.

Would be

function validaName(el) {
  var name = el.files[0].name
  if (name != 'newFile.mpg') {
    console.log('erro: O nome do arquivo é: ' + name)
  }
}
Upload: <input type="file" onchange="validaName(this)" />

Browser other questions tagged

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