java – How to do zip code validation for Android


I would like to know how I validate a zip code typed by the user in an EditText on Android. Do I need any specific API? I want to validate if the zip code exists and return to the screen if it isn't.


If you have the formula for validating the zip code at hand, you can do this in the class.

Capture her text using

TextView textoCEP = (TextView) rootView.findViewById(<suaEditText>);

Then String that text by capturing it with <sua editText>.getText(); Maybe you need to use .toString(); because they usually return CharSequences .

If not, it's something right along those lines. I hope I can help you.

EDIT: So Validating ZIP Codes is kind of complicated. You can check that the zip code has the right number of digits, which are 8, and format it using a substring (Seen on the internet/not tested):

        if (cep.Length == 8) {
            cep = cep.Substring(0, 5) + "-" + cep.Substring(5, 3);

However, the final three digits indicate the state that zip code comes from. As it would be too big to paste all the numbers here, here's something similar in a forum I saw on Google. It's not in Java, but you should be able to get the idea:

Scroll to Top