criticize error when CEP is invalid (via CEP)

0

Hello

I'm using the code below to get an address through the informed CEP.

It works, however when typing an invalid zip code or 0000000, I get the {"erro":true} return. How can I turn this return into an alert with the code below:

	console.log("webservice cep");
	
	$("#numero").attr("readOnly", true);
	$("#complemento").attr("readOnly", true);
	//var lastCepCheck = '';
	var ultimo_cep = '';
	document.getElementById('cep').addEventListener('keyup', function() {
	    //Impede inserir algo alem de Números
	    //this.value = this.value.replace(/[^0-9]/, "");

	    //Pega apenas os números
	    var cep = this.value.replace(/[^0-9]/, "");

	    //Só pesquisa se tiver 8 caracteres e o ultimo cep pesquisado seja diferente do atual.
	    if (cep.length != 8 || ultimo_cep == cep) {
	        return false;			
	    }
	    ultimo_cep = cep;

	    ajax = new XMLHttpRequest();

	    var url = "http://viacep.com.br/ws/" + cep + "/json/";
	    ajax.open('GET', url, true);
	    ajax.send();

	    ajax.onreadystatechange = function() {
			//console.log(ajax.status);
	        if (ajax.readyState == 4 && ajax.status == 200) {
	            var json = JSON.parse(ajax.responseText);				
	            console.log(ajax.responseText);
				if (json == "{erro: true}"){
					alert("erro");
				}
				else {
				$("#logradouro").val(json.logradouro);
				$("#bairro").val(json.bairro);
				$("#cidade").val(json.localidade);
				$("#uf").val(json.uf);
				$("#numero").attr("readOnly", false);
				$("#complemento").attr("readOnly", false);
				$("#numero").focus();
	            }
	        } 
	    }
	});
    
asked by anonymous 24.06.2017 / 02:27

2 answers

2

There may be other more streamlined methods, but this also works. Just convert to String the return of the error that is in JSON and do the verification:

if (JSON.stringify({erro: true}) == '{"erro":true}')
  alert("erro");

Edited:

if (JSON.stringify(json) == '{"erro":true}')
  {alert("erro");}
    
24.06.2017 / 02:53
1

You can use the hasOwnProperty() function to check for the "error" index on the value returned by API ;

var json = JSON.parse(ajax.responseText);
if (json.hasOwnProperty('error')) {
    console.log(json.error);
}
...
    
24.06.2017 / 04:10