Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
    }
}
like image 896
Oscar Méndez Avatar asked Apr 23 '13 04:04

Oscar Méndez


4 Answers

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.? ]*"

like image 104
Dhaval Parmar Avatar answered Nov 15 '22 08:11

Dhaval Parmar


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;
}
like image 31
sivi Avatar answered Nov 15 '22 08:11

sivi


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) {}
   });
like image 38
manDroid Avatar answered Nov 15 '22 08:11

manDroid


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..:)

like image 28
umair.ali Avatar answered Nov 15 '22 10:11

umair.ali