keshav kowshik
keshav kowshik

Reputation: 2374

How to check for initial spaces in the text entered in edit text android

I have an issue in validating edit text in my android application. I have tried many methods and none of them are suiting my scenario. When user tries to save the post the entering only spaces in edit text field I need to pop out an error message. But I am able to check the condition where user enters only spaces.

I have used the following methods:

if(subjectText.isEmpty() || detailsText.isEmpty() || subjectText.equals(" ") || detailsText.equals(" ")){

// perform operation.

}

Here the .equals(" ") method checks only for one space. If the user entry is some thing like " " and not text, how can I check tell the user there is not text. Please any one let me know. All suggestions are welcome.

I have also tried with .contains(" ") method, this method solves the problem but even if there is space in between text it pops the error which should not happen. If the user entry is "how are you", the .contains(" ") method give an error.

How can I solve this issue. Please help me come out of this issue.

Upvotes: 0

Views: 3404

Answers (4)

Oliver Sanz
Oliver Sanz

Reputation: 46

Try this:

final String subjectText = "  foo   ";
if (subjectText.replaceFirst("\\s+$", "").length() == 0) {

// perform operation.

}

Code from here

Upvotes: 0

Jera Balais
Jera Balais

Reputation: 61

try this, to remove all the whitespace that you have entered from the EditText

if(subjectText.trim().length()<1){
   //perform action
}

Upvotes: 0

mgokgoz
mgokgoz

Reputation: 186

Make a regex check for that. Like this that checks for whitespaces;

if(... || subjectText.matches("^\\s*$") || ... }

For white space you can also do

subjectText.trim().lenght==0

Upvotes: 0

reidzeibel
reidzeibel

Reputation: 1632

You can use startsWith(" ") to detect whitespace at the beginning of a string.

Edit :

maybe like this

if(subjectText.isEmpty() || detailsText.isEmpty() || subjectText.startsWith(" ") || detailsText.startsWith(" ")){

// perform operation.

}

Upvotes: 4

Related Questions