[Opcional] To facilitate dependency management, I recommend using Boss. boss install github.com/viniciussanchez/viacep
Add the following folder to your project in Project> Options> Resource Compiler> Directs and Condiçonals> Include File Search Path
../viacep/src
You will need to do the use of the following Units: ViaCEP.Intf , ViaCEP.Core , ViaCEP.Model
uses ViaCEP.Intf, ViaCEP.Core, ViaCEP.Model; When consulted an invalid format zip code, for example: 950100100 (9 digits), 95010A10 (alphanumeric), 95 01010 (space), the return will be nil .
The method of validating whether it is a valid zip code or not, just make sure that the informed zip code has 8 digits and that all are numerical and can be accessed before consulting the WebService through the IViaCEP interface using the Validate method.
When consulted a valid but nonexistent format zip code, for example: 99999999 , the return will also be nil . This means that the zip code consulted was not found in the database.
Example:
var
ViaCEP: IViaCEP;
begin
ViaCEP := TViaCEP.Create;
if ViaCEP.Validate( ' 01001000 ' ) then
ShowMessage( ' CEP válido ' )
else
ShowMessage( ' CEP inválido ' );
end ; Remember that in the above method, it is not necessary to destroy the created instance of the TViaCEP class, because it is using an Interface .
var
ViaCEP: IViaCEP;
CEP: TViaCEPClass;
begin
ViaCEP := TViaCEP.Create;
// Aqui você pode chamar a rotina para validar se é um CEP válido.
CEP := ViaCEP.Get(edtCEPConsultar.Text);
if not Assigned(CEP) then
Exit; // Aqui você pode exibir uma mensagem para o usuário falando que o CEP não foi encontrado.
try
edtJSON.Lines.Text := CEP.ToJSONString;
edtCEP.Text := CEP.CEP;
edtLogradouro.Text := CEP.Logradouro;
edtComplemento.Text := CEP.Complemento;
edtBairro.Text := CEP.Bairro;
edtLocalidade.Text := CEP.Localidade;
edtUF.Text := CEP.UF;
edtDDD.Text := CEP.DDD;
edtIBGE.Text := CEP.IBGE;
edtGIA.Text := CEP.GIA;
finally
CEP.Free;
end ;
end ; Once you make the zip code consultation, you can get the returned content in JSON format using the .tojsonstring method available in the TViaCEPClass class. See the example below, where a TMemo is populated with the contents of the query:
var
CEP: TViaCEPClass;
begin
Memo.Lines.Text := CEP.ToJSONString;
end ; {
"cep": "01001-000",
"logradouro": "Praça da Sé",
"complemento": "lado ímpar",
"bairro": "Sé",
"localidade": "São Paulo",
"uf": "SP",
"ddd": "",
"ibge": "3550308",
"gia": "1004"
}
Access the form and update online: update zip code
Origin IBGE Code of Municipalities: Access Site
Origin GIA/ICMS Code (SP Available only): view pdf (pp.137)
Viacep - Free WebService Cep and IBGE: Access Site
