Input validation in Java

java.util.Scanner is a simple text parser.  It breaks input into tokens that you request.  It can help you with: primitive types (boolean, byte, double, float, int, long, short), and strings that match regular expressions.  This function is also available on Android Java.

Example:

Scanner s = new Scanner("CAFE false");
System.out.println(s.nextInt(16));
System.out.println(s.nextBoolean());

Prints

51966
false

You can also work with regular expressions using String.matches().  s.matches(“regex”) returns true if the entire string matches the expression.  s.split(“regex”) returns an array of substrings divided at “regex” (the character(s) matching “regex” are not included).

Example

String s = "The food is in the barn.";
Boolean b;
b = s.matches("foo.*bar"); // false
b = s.matches("The.*barn."); // true

You can also work with regular expressions using the java.util.regex package.  You use java.util.regex.Pattern() to set the regular expression to match.  You use the returned Matcher to test matches and perform other related operations.

You should be aware of the worst-case complexity of their expression. Some can be exponential and lead to a DoS vulnerability.

String s = "The food is in the barn.";
Pattern p = Pattern.compile("foo.*bar");
Matcher m = p.matcher(s);
b = m.matches(); // false
b = Pattern.compile("The.*barn.").matcher(s).matches(); // true
b = Pattern.matches("The.*barn.",s); // true

Published by

Kenneth Ingham

Kenneth has been working with security since the early 1980s. He was a system administrator when the Morris Worm was released, and one of his work areas was helping secure the systems. Since then, Kenneth has studied network and computer security, and spent many, many hours looking at how software fails. With knowledge about failures, he can help you produce software that is less likely to suffer a security breach. Kenneth has a Ph.D. in Computer Science, and his research topic was on computer security. Kenneth has helped developers creating systems for financial services institutions, telecommunications companies, and embedded system and process control.

Leave a Reply

Your email address will not be published. Required fields are marked *