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

前端 未结 6 1827
既然无缘
既然无缘 2021-01-01 01:06

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 char

相关标签:
6条回答
  • 2021-01-01 01:27

    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;
    }
    
    0 讨论(0)
  • 2021-01-01 01:30

    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.

    0 讨论(0)
  • 2021-01-01 01:44

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

    0 讨论(0)
  • 2021-01-01 01:49

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

    0 讨论(0)
  • 2021-01-01 01:50

    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) {}
       });
    
    0 讨论(0)
  • 2021-01-01 01:51

    Use:

    public void click (View view) {
    
        if (edittext.matcher(abcd).find ()) {
           Toast.maketext(this, "abcd Found", TOAST.LENGTH_LONG).show ();
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题