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


you can use



input.matches("[A-Za-z0-9.]+")

      

+3


a source


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


Try the following:

private boolean isBasicLatin(String input)
{
    for (char c : input.toCharArray())
    {
        if (!UnicodeBlock.BASIC_LATIN.equals(UnicodeBlock.of(c)))
        {
            return false;
        }
    }

    return true;
}

      

0


a source







All Articles