웹개발시 입력값의 길이를 체크할때
string.length 를 이용하면 무조건 한글이건 영문이건
1글자로 체크함.
서버측에서 실제 저장할때는 알파뉴메릭(숫자, 영문자, 아스키코드 등)은 1byte, 한글 및 특수문자는 2byte로 처리함으로
한글이 포함된경우 폼에서 자바스크립트로 체크하더라도
데이터베이스에 저장할때 에러가 나죠
한글,특수문자를 2자리로 계산해서 폼에서 체크하도록 한
예제입니다.
<html>
<head>
<title> new document </title>
</head>
<script language="JavaScript">
<!--
function check()
{
var string = document.a.test.value;
alert(getStringLength(string));
}
// 문자열 길이 체크 알파뉴메릭(1자리), 한글(2자리)
function getStringLength (str)
{
var retCode = 0;
var strLength = 0;
for (i = 0; i < str.length; i++)
{
var code = str.charCodeAt(i)
var ch = str.substr(i,1).toUpperCase()
code = parseInt(code)
if ((ch < "0" || ch > "9") && (ch < "A" || ch > "Z") && ((code > 255) || (code < 0)))
strLength = strLength + 2;
else
strLength = strLength + 1;
}
return strLength;
}
//-->
</script>
</head>
<body>
<form name="a">
<input type="text" name="test"><input type="button" value="체크" onClick="JavaScript:check();">
</form>
</body>
</html>
'Html-JavaScript' 카테고리의 다른 글
[알고리즘] 윤년이야기 (0) | 2007.01.09 |
---|---|
[JavaScript] 윤년체크(그래고리력) (0) | 2007.01.09 |
숫자 데이터중에서 Comma(,) 를 전부 없애는 함수 (0) | 2007.01.09 |
소수점 자리가 있는 숫자 중에서 Comma(,)를 붙이는 함수 (0) | 2007.01.09 |
[JavaScript] 숫자체크 (0) | 2007.01.09 |