Created
February 26, 2012 14:01
-
-
Save froop/1916970 to your computer and use it in GitHub Desktop.
[Java] TextBox入力検証
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static boolean validateTextBox(String text, int limitBytes) { | |
return !containsControl(text) && !isOverBytes(text, limitBytes); | |
} | |
public static boolean validateTextArea(String text, int limitBytes) { | |
return !containsInvisible(text) && !isOverBytes(text, limitBytes); | |
} | |
private static boolean containsControl(String text) { | |
return !text.matches("\\P{Cntrl}*"); | |
} | |
private static boolean containsInvisible(String text) { | |
return !text.matches("[\\P{Cntrl}\\p{Space}]*"); | |
} | |
private static boolean isOverBytes(String text, int limit) { | |
return countBytes(text) > limit; | |
} | |
private static final String CHAR_ENCODE = "UTF-8"; | |
private static int countBytes(String text) { | |
try { | |
return text.getBytes(CHAR_ENCODE).length; | |
} catch (UnsupportedEncodingException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
@Test | |
public void testValidateTextBoxOK() { | |
assertTrue(validateTextBox("ab cd", 5)); | |
assertTrue(validateTextBox("α", 2)); | |
assertTrue(validateTextBox("あ", 3)); | |
assertTrue(validateTextBox("𠀋", 4)); | |
assertTrue(validateTextBox("", 0)); | |
} | |
@Test | |
public void testValidateTextBoxNgBytes() { | |
assertFalse(validateTextBox("ab cd", 4)); | |
assertFalse(validateTextBox("α", 1)); | |
assertFalse(validateTextBox("あ", 2)); | |
assertFalse(validateTextBox("𠀋", 3)); | |
} | |
@Test | |
public void testValidateTextBoxNgChar() { | |
assertFalse(validateTextBox("\0", 5)); | |
assertFalse(validateTextBox("a\t", 5)); | |
assertFalse(validateTextBox("\rb", 5)); | |
assertFalse(validateTextBox("a\nb", 5)); | |
} | |
@Test | |
public void testValidateTextAreaOK() { | |
assertTrue(validateTextArea("\t", 1)); | |
assertTrue(validateTextArea("\r", 1)); | |
assertTrue(validateTextArea("\n", 1)); | |
assertTrue(validateTextArea("あ", 3)); | |
assertTrue(validateTextArea("aあ \t\n\f\r", 9)); | |
assertTrue(validateTextArea("", 0)); | |
} | |
@Test | |
public void testValidateTextAreaNG() { | |
assertFalse(validateTextArea("ab", 1)); | |
assertFalse(validateTextArea("\0", 1)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment