开发者

How to ensure that no non-ascii unicode characters are entered?

开发者 https://www.devze.com 2022-12-28 08:54 出处:网络
Given a java.lang.String instance, I want to verify that it doesn\'t contain any unicode characters that are not ASCII alphanumerics. e.g. The string should be limited to [A-Za-z0-9.]. What I\'m doing

Given a java.lang.String instance, I want to verify that it doesn't contain any unicode characters that are not ASCII alphanumerics. e.g. The string should be limited to [A-Za-z0-9.]. What I'm 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 in开发者_JAVA技巧valid" );
}

Is there a better way to solve this ?


You can use

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


Yes, there's a better way to solve that. You already have written the pattern, so why don't you use a regular expression to validate it? Instead of throwing an exception that includes the invalid character you could just aswell use a generic error message saying something along the lines of "input contains invalid characters (valid characters are a-z and 0-9)".


Try this:

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

    return true;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消