How to detect special characters in edit text and display Toast in response (Android)?

Sorry for my bad English, I use Google translation.

I create an activity in which users must create a new profile. I place a restriction on editing text of 15 characters, and I want a warning if a new profile name has spaces or special characters. Like online video games

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

I need help identifying special characters and displaying 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();
    }
}
+5
source share
4 answers

You can use:

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

true, a-z, A-Z, , .

:

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
            }

        }
    }

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

+13

Android Saripaar, API Android. : 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;

api , . [^a-zA-Z0-9] [\\W+] .

, ..:)

+1

edittext xml , ;

 android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

If you need a 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) {}
   });
+1
source

If you want to pick up special characters and support more than just a very violin set of English letters 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;
}
0
source

All Articles