How to ensure that no un-ascii unicode characters are entered?
Given an instance of java.lang.String, I want to check that it does not contain unicode characters that are not ASCII alphanumeric characters. eg The string must be terminated by [A-Za-z0-9.]. What I am doing now is something very inefficient:
import org.apache.commons.lang.CharUtils;
String s = ...;
char[] ch = s.toCharArray();
for( int i=0; i<ch.length; i++)
{
if( ! CharUtils.isAsciiAlphanumeric( ch[ i ] )
throw new InvalidInput( ch[i] + " is invalid" );
}
Is there a better way to solve this problem?
+2
a source to share
3 answers
Yes, there is a better way to solve this. You already wrote a pattern, so why not use a regular expression to test it? Instead of throwing an exception that includes an invalid character, you could simply use a generic error message saying something along the lines of "input contains invalid characters (valid characters are az and 0-9)".
+1
a source to share