增加字节长度验证,应对数据库字节长度与java串长度算法不一致的问题

This commit is contained in:
hellozrh
2022-08-09 15:30:52 +08:00
parent b8977ea119
commit ad09bd41bb
2 changed files with 48 additions and 0 deletions

View File

@@ -4,6 +4,8 @@ import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.lang.id.IdUtil;
import cn.hutool.core.regex.PatternPool;
import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.CharsetUtil;
import org.junit.Assert;
import org.junit.Test;
@@ -273,6 +275,22 @@ public class ValidatorTest {
Validator.validateLength(s1, 6, 8, "请输入6到8位的字符"));
}
@Test
public void validateByteLengthTest() {
String s1 = "abc";
int len1 = StrUtil.byteLength(s1, CharsetUtil.UTF_8);
Assert.assertEquals(len1, 3);
String s2 = "我ab";
int len2 = StrUtil.byteLength(s2, CharsetUtil.UTF_8);
Assert.assertEquals(len2, 5);
//一个汉字在utf-8编码下占3个字节。
Assert.assertThrows(ValidateException.class, ()->
Validator.validateByteLength(s2, 1, 3, "您输入的字符串长度超出限制!")
);
}
@Test
public void isChineseNameTest(){
Assert.assertTrue(Validator.isChineseName("阿卜杜尼亚孜·毛力尼亚孜"));