How to do zip validation for Android

Asked

Viewed 1,073 times

3

I would like to know how I validate a cep typed by the user in an Edittext on Android. Do I need a specific API? I want to validate if the zip code is existing and return to the screen if it is not.

2 answers

1


If you have the formula to validate the ZIP code on hand, you can do this in the class.

Capture her text using

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

So put in a String that text capturing you with a <sua editText>.getText(); You may need to use .toString(); because they usually return CharSequences.

If it’s not that, it’s something along those lines. I hope I can help you.

EDIT: So, Validate Zip Codes is kind of tricky. You can check if the zip code has the right number of digits, which are 8, and format it using a substring (Viewed on internet/untested):

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

However, the final three digits indicate the state from which that zip code comes. Since it would be very big to paste all the numbers here, follow something similar in a forum I saw on Google. It’s not in Java, but you should be able to get the idea: http://www.devmedia.com.br/dicas-validando-cep/833

  • Cast a EditText for a TextView works because both use texts.

  • What I don’t have is just the validation code. I wondered if it was by post office api or something.

  • @Felipemiranda, I edited my answer. I hope it’s what you’re looking for.

  • Thank you! That’s what I’m looking for, but I want to see if it’s an existing zip code as well. I’ll analyze the link you sent me.

  • @Felipemiranda, if my answer helped, mark it later. But, if the answer was something other than what I said and you found, answer your own question, so other Sopt users can be sure! Hug.

  • Dude, I can’t use the substring method. Remembering that I’m picking up the zip code of an Edittext that the user informs.

Show 1 more comment

0

You can use this class available on Github as an example project.

String zipcode = editText.getText().toString();
    Pattern pattern_zipcode = Pattern.compile("(^\\d{5}-\\d{3}|^\\d{2}.\\d{3}-\\d{3}|\\d{8})");
    Matcher matcher = pattern_zipcode.matcher(zipcode);
    if(zipcode.equals("")){
        editText.setError("O campo não pode estar vazio");
        editText.requestFocus();
        // Faça aqui sua ação caso o campo esteja vazio.
    }
    if (!matcher.matches()) {
        editText.setError("Informe um CEP válido");
        editText.requestFocus();
        // Faça aqui sua ação caso seja o CEP invalido.
    } else {
        // Caso esteja tudo OK realize a ação aqui.
    }

Using the REGEX that is in Pattern, if you want other formats you can search for them on this site here.

Browser other questions tagged

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