웹개발시 입력값의 길이를 체크할때

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>



+ Recent posts