How to detect special characters in an edit text and display a Toast in response (Android)?
Asked Answered
D

6

7

An apology for my bad English, I'm using google translate.

I'm creating an activity in which users must create a new profile. I put a limit to edit text of 15 characters and I want that if the new profile name has spaces or special characters display a warning. As online video games

The following code helps me to detect spaces, but not special characters.

I need help to identify special characters and display a warning in response.

@Override
public void onClick(View v) {
    //Convertimos el contenido en la caja de texto en un String
    String nombre = nombreUsuario.getText().toString();

    //Si el tamaño del String es igual a 0, que es es lo mismo que dijeramos "Si esta vacio"
    if (nombre.length() == 0) {
        //Creamos el aviso
        Toast aviso = Toast.makeText(getApplicationContext(), "Por favor introduce un nombre de Usuario", Toast.LENGTH_LONG);
        aviso.show();

    } else if (nombre.contains(" ") | nombre.contains("\\W")) {
        Toast aviso = Toast.makeText(getApplicationContext(), "No son permitidos los espacios ni los caracteres especiales", Toast.LENGTH_LONG);
        aviso.show();
    } else {
        nombre = nombreUsuario.getText().toString();
        //Conectamos con la base de datos
        //Creamos un bojeto y lo iniciamos con new
        Plantilla entrada = new Plantilla(CrearUsuarioActivity.this);
        entrada.abrir();

        //creamos un metodo para escribir en la base de datos (crear entradas)
        entrada.crearEntrada(nombre);
        entrada.cerrar();
    }
}
Distorted answered 23/4, 2013 at 4:29 Comment(2)
you can use similar way as u r using for space like .contains("$") in this way.Hollins
Try using InputFilter developer.android.com/reference/android/text/InputFilter.htmlThew
N
23

You can use:

string.matches("[a-zA-Z.? ]*")

That will evaluate to true if every character in the string is either a lowercase letter a-z, an uppercase letter A-Z, a period, a question mark, or a space.

like:

public void Click(View v) {
        if (v.getId() == R.id.button1) {
            String nombre = textMessage.getText().toString();
            if (nombre.length() == 0) {

                // Creamos el aviso
                Toast aviso = Toast.makeText(getApplicationContext(),
                        "Por favor introduce un nombre de Usuario",
                        Toast.LENGTH_LONG);
                aviso.show();

            } else if (!nombre.matches("[a-zA-Z.? ]*")) {
                Toast aviso = Toast
                        .makeText(
                                getApplicationContext(),
                                "No son permitidos los espacios ni los caracteres especiales",
                                Toast.LENGTH_LONG);
                aviso.show();

            } else {

                // Do what ever you want
            }

        }
    }

for allow a-z, A-Z, 0-9 use "[a-zA-Z0-9.? ]*"

Neary answered 23/4, 2013 at 4:58 Comment(1)
This will work only with ascii and a charcter like ñ or א won't pass this filter.Gabrielson
G
4

If you want to pick up the special chars and support more than just the very resrictive set of English alpha bet and numbers:

String edit_text_name = YourEditTextName.getText().toString();

Pattern regex = Pattern.compile("[$&+,:;=\\\\?@#|/'<>.^*()%!-]");

if (regex.matcher(edit_text_name).find()) {
        Log.d(TAG, "SPECIAL CHARS FOUND");
        //handle your action here toast message/ snackbar or something else
        return;
}
Gabrielson answered 28/2, 2017 at 14:11 Comment(0)
I
3

use the the following line in edittext in xml file so that it only enters the alphabets and numbers;

 android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

If you need dynamic response use textwatcher for your edittext;

   yourEditText.addTextChangedListener(new TextWatcher() {

      public void afterTextChanged(Editable s) {

       // Here you need to check special character, if found then show error message

      if (s.toString().contains("%"))
      {
           // Display error message
      }

      public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

      public void onTextChanged(CharSequence s, int start, int before, int count) {}
   });
Intercalate answered 4/5, 2015 at 11:34 Comment(0)
E
1

You shoud go for Android Saripaar, a very light weight and simple API for android. In your case, you can do following stuff on you EditText instence...

@TextRule(order = 1, minLength = 15, message = "Enter atleast 15 characters.")
@Regex(order = 2, pattern = "[\\W+]", message = "Special characters are not allowed.")
private TextView yourEditText;

using this api will lead you to have more contorls on you validation process in proper way. you can also use [^a-zA-Z0-9] instead of [\\W+] as your reguler expression pattern.

Hope this helps..:)

Extraditable answered 23/4, 2013 at 5:6 Comment(0)
Z
1

As I can´t comment on other posts, I will complement the most voted answer with a tip for a more fashion visual resolution.

First, pass the Edittext (etNombre) data to a String variable. Ex: String nombre = etNombre.getText().toString();

Then, use an if to verify:

if (!nombre.matches("[a-zA-Z.? ]*")) {

    etNombre.setError("Your message here");

}

this solution will set an "!" icon on the Edittext and it's much better than a Toast because the message is pointing the user to the error.

Zeeba answered 19/11, 2018 at 15:30 Comment(0)
G
-1

Use:

public void click (View view) {

    if (edittext.matcher(abcd).find ()) {
       Toast.maketext(this, "abcd Found", TOAST.LENGTH_LONG).show ();
    }

}
Gamb answered 31/5, 2018 at 18:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.