Android snippet: validate a hex number input

This is how you can validate a hex input in android code. The regex it makes use of can be used in other languages as well.

Validation steps are :

  • check if the input is not null or zero length
  • check if the input has even numbers as hex numbers are always even
  • match the input with the validating regex.
public boolean validHexInput(String str) {

   if (str == null || str.length() == 0) {
      return false;
   }

   // length should be even number 
   // otherwise its not a valid hex 
   if (str.length() % 2 == 0) {
      String var1 = "(?i)[0-9a-f]+";
      return str.matches(var1);
 }

 return false;
}