1

I'm trying to validate a TextView so that it can only contain alphabets and .

So far what I've done are it does not allow spaces and it cannot be left blank, so how do I carry on with not allowing numbers and special characters except for .

              if (PatientInitials.getText().toString().equals(""))
              {
                  final Toast toast = Toast.makeText(getApplicationContext(), "Please enter the patient initials.", Toast.LENGTH_SHORT);
                    toast.show();
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                       @Override
                       public void run() {
                           toast.cancel(); 
                       }
                }, 3000);
              }
              else if (PatientInitials.getText().toString().matches(".*([ \t]).*"))
              {
                  final Toast toast = Toast.makeText(getApplicationContext(), "Patient initials cannot contain spaces.", Toast.LENGTH_SHORT);
                    toast.show();
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                       @Override
                       public void run() {
                           toast.cancel(); 
                       }
                }, 3000);
              }
                      //Below doesn't work
              else if (PatientInitials.getText().toString().matches("/^[A-z]+$/"))
              {
                  final Toast toast = Toast.makeText(getApplicationContext(), "Patient initials cannot contain numbers and special characters.", Toast.LENGTH_SHORT);
                    toast.show();
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                       @Override
                       public void run() {
                           toast.cancel(); 
                       }
                }, 3000);
Spencer
  • 111
  • 3
  • 10
  • Would a space be allowed or not? Usually you would use `^[a-zA-Z.]+$` for (at least one) lower case letters, upper case letters, and period. – Floris Nov 19 '13 at 03:59

2 Answers2

3

Try this :

            EditText state = (EditText) findViewById(R.id.txtState);
            Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
            Matcher ms = ps.matcher(state.getText().toString());
            boolean bs = ms.matches();
            if (bs == false) {
                if (ErrorMessage.contains("invalid"))
                    ErrorMessage = ErrorMessage + "state,";
                else
                    ErrorMessage = ErrorMessage + "invalid state,";
            }

Hope this helps.

Siddharth_Vyas
  • 9,972
  • 10
  • 39
  • 69
0

Have you taken a look at android:digits to pre-emptively only whitelist certain characters?

See also: https://stackoverflow.com/a/6082975/452383

Community
  • 1
  • 1
Andrew Flynn
  • 1,501
  • 12
  • 17