Show error if user enters only spaces in EditText - Android

I want to show an error if the user enters spaces in the EditText, but I do not know how to do this?

Here is my simple job

if (tName.getText().toString().matches(" ")) { Toast.makeText(MainActivity.this, "Must Add Your Name Here", Toast.LENGTH_SHORT).show(); } 
+10
android validation android-edittext
source share
7 answers

for me I use trim.Trim will remove the first and last space of the line entered by the user.

 String tName = tName.getText().toString.trim(); if(tName.matches("")){ Toast.makeText(MainActivity.this, "Must Add Your Name Here", Toast.LENGTH_SHORT).show(); } 
+5
source share

Try with this code.

  if(!editText.getText().toString().trim().isEmpty()){ editText.setError("Empty spaces are not allowed"); editText.setFocusable(true); Toast.makeText(MainActivity.this, "Must Add Your Name Here", Toast.LENGTH_SHORT).show(); } 
+2
source share

check the following code.

 String name = tName.getText().toString(); if(name != null && !name.isEmpty()){ Toast.makeText(MainActivity.this, "Name"+name, Toast.LENGTH_SHORT).show(); }else{Toast.makeText(MainActivity.this, "Must Add Your Name Here", Toast.LENGTH_SHORT).show();} 
0
source share

use this to check space in Edittext

 string name = "Paul Creasey";//edittext.gettext.tostring(); if (name.contains(" ")) { //use this to show any msg } 
0
source share

try it

 if(tName.getText().toString().trim().isEmpty()){ //your code for handing white space } 
0
source share
  String strName = tName.getText().toString().trim(); if(TextUtils.isEmpty(strName)) { tName.setError("Enter Your Name"); return; 

try it

0
source share

This solution also makes my field mandatory for example, "You must add your name here." In my case, I am looking for a solution in which I have a name field, but I only want to prevent the user from entering empty spaces, no matter how much they want to fill in their name or not, but they cannot enter empty spaces.

So below code works for me

  public static boolean checkForEmptySpaces(String value){ if (value.length()>0 && value.trim().matches("")) { showToast(v.getContext(), "Empty spaces are not allowed!"); return false; }else { return true; } } 
0
source share

All Articles