I would like to complement the response of @Renan with a genuine validation.
Although the Brazilian CEP is not defined by an algorithm itself, but only one Structured decimal representation of Country , as any logical structure it follows a standard validable by Regular Expressions.
Note that I have written Regular Expressions , in the plural, since we have 26 states + a Federal District that, in one structure, result in 27 different standards.
Years ago, when I was searching for alternatives to autocomplete information based on a zip code, in an "era" where there were not many WebServices available and / or trusted, I ended up finding the database itself used by the Post Office to download in a blog that no longer exists.
The important thing is that amidst the comments of the article there was one of none other than Aurélio Marinho Jargas , author of the best reference book for Expressions Regular in Portuguese.
And in this particular comment he published these 27 Regular Expressions which I quickly dealt with implementing in PHP. Calm, cocada ...
Despite the relative difficulty I had in porting the code to JavaScript, I did, and I leave it as a reference for community in JSFiddle .
After the basic length check, the State is first checked by a Regular Expression apart. Only then did we test the first five digits of the CEP, which are the ones that matter against the Regular Expression of the informed state.
All credit goes to Master Aurelius, I just packed everything like a good Padawan. ^ _ ^