I had met this issue. In my case, my customers want our application should allow some characters in German and French even not allow some special characters.
The solution is that we limit the allowed characters by showing the validation message on GUI. For an instance, the message looks like the following:
"This field can't contain any special characters; only letters, numbers, underscores (_), spaces and single quotes (') are allowed."
I used Regular Expression to check it. For entering Germany and French, I actually don't have this type of keyboard, so I referred these sites:
* German characters: http://german.typeit.org/
* French characters: http://french.typeit.org/
Here is my code:
package vn.nvanhuong.practice;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SpecialCharactersUtil {
private SpecialCharactersUtil(){}
public static boolean isExistNotAllowedCharacters(String source){
Pattern regex = Pattern.compile("^[a-zA-Z_0-9_äöüÄÖÜùûüÿàâæéèêëïîôœÙÛÜŸÀÂÆÉÈÊËÏÎÔŒ' ]*$");
Matcher matcher = regex.matcher(source);
return !matcher.matches();
}
}
And, some tests:
package vn.nvanhuong.practice.test;
import static org.junit.Assert.*;
import org.junit.Test;
import vn.nvanhuong.practice.SpecialCharactersUtil;
public class SpecialCharactersUtilTest {
@Test
public void shoulDetectSpecialCharacters() {
String source = "~`!@#$%^&*()-+={}\\[\\]\\|:;\"<>,./?";
assertTrue(SpecialCharactersUtil.isExistNotAllowedCharacters(source));
}
@Test
public void shoulAllowGermanCharacters() {
String source = "äöüÄÖÜ";
assertFalse(SpecialCharactersUtil.isExistNotAllowedCharacters(source));
}
@Test
public void shoulAllowFrenchCharacters() {
String source = "ùûüÿàâæéèêëïîôœÙÛÜŸÀÂÆÉÈÊËÏÎÔŒ";
assertFalse(SpecialCharactersUtil.isExistNotAllowedCharacters(source));
}
@Test
public void shoulAllowAlphanumericAndSpacesAndUnderscoreAndSingleQuote() {
String source = "character' special_1";
assertFalse(SpecialCharactersUtil.isExistNotAllowedCharacters(source));
}
}
Now, we can use the method for our validation on GUI.