0

I need to set an error for a password field with the condition "Only 2~22 characters and symbols , _ - are allowed."

But I am a little stuck here.

Here is what I got so far:

if(
  !(editText.length() >= 2 && editText.length() <= 22 ) ||
    !(editText.contains("-") || editText.contains("_") || editText.contains(","))
  ) {
  //set error message
}

But the problem is that if I input a symbol other than , _ or -, the error message still doesn't show. For the input length, the error message shows as it should though.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
coffeeak
  • 2,980
  • 7
  • 44
  • 87

5 Answers5

4

In java, use :

editText.matches("^[A-Za-z,_\\-]{2,22}$");
Darren
  • 722
  • 4
  • 12
1

Your || or commands for the hyphen, underscore, and comma are making it that the user has to include at least one of each of those characters.

You also aren't checking for a list of valid characters. A-Z? 0-9? a-z? You will want to look at the Package java.util.regex package or iterate over the String and check each character.

Mark Stewart
  • 2,046
  • 4
  • 22
  • 32
1

There is the problem with ur logic, use && after <= 22 ) in place of || Try this:

if(!((editText.length() >= 2 && editText.length() <= 22 ) && (editText.contains("-") || editText.contains("_") || editText.contains(","))))
A. Sinha
  • 2,666
  • 3
  • 26
  • 45
1

I believe you can use Regex for this while researching I came accross Regex Library for Strong Password

You can implement below regex for your purpose

^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[a-z]).{2,22}$

Explanation:

^                         Start anchor
(?=.*[A-Z].*[A-Z])        Ensure string has uppercase letters.
(?=.*[!@#$&*])            Ensure string has one special case letter.
(?=.*[a-z]) Ensure string has lowercase letters.
.{2,22}                   Ensure string is of 2 char long and Max of 22.
$                         End anchor.

Implementation

if(editText.matches(^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[a-z]).{2,22}$))
{
  //set error message
}
Shweta Pathak
  • 775
  • 1
  • 5
  • 21
0

You can probably use a regex.

But otherwise, you'll need to iterate through the string to insure that no character is < 'a' or > 'z' and not ('_' or '-').

As far as the "length" check, this might be a bit more readable:

(editText.length() < 2 || editText.length() > 22 ) 

But again - I'd encourage you to consider using a regex:

http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

paulsm4
  • 114,292
  • 17
  • 138
  • 190