KICK LAB

킥랩

직접 만들어 본 라이브러리와 예제를 바로 실행해 보는 실험실. 킥노트가 글이라면, 킥랩은 눌러 보는 코드입니다.

2015년 JavaScript

_STJ.js — 자주 쓰는 함수 모음

문자열·검증·날짜·쿠키처럼 매번 다시 짜던 함수를 모아 만든 개인 라이브러리. 직접 눌러보는 놀이터.

▶ 실행 화면 새 창으로 ↗

2015년, 프로젝트마다 똑같은 함수를 복사해 붙이는 일이 지겨워서 만든 개인 함수 모음입니다. 이름은 _SongToryJavascript 의 줄임말입니다. jQuery 없이도 쓸 수 있도록 순수 JavaScript로만 작성했습니다.

들어 있는 것

묶음 함수
STRING trim, nl2br, htmlspecialchars, byteFormat, numberFormat
validRule require, alpha, number, alphaNum, email, ip, url
FORM valid(form, field, rule, msg) — 폼 검증 (라디오·체크박스 개수 포함)
DATE format, week, d_day
browser check, ieVer, isMobile
COOKIE set, get, del
EVENT show, hide, toggle
_STJ.STRING.numberFormat(1234567);        // "1,234,567"
_STJ.validRule.email('[email protected]');   // true
_STJ.DATE.week('2015-04-02', 'KR');       // "목"

지금 보면

  • DATE.format이 월을 하나 적게 출력합니다. getMonth()가 0부터 시작한다는 점을 빠뜨렸습니다. 놀이터에서 바로 확인할 수 있습니다.
  • htmlspecialchars의 &lt 뒤에 세미콜론이 빠져 있습니다.
  • browser.check()는 IE를 가려내려고 만든 함수입니다. 지금은 navigator.userAgentData나 기능 감지(feature detection)를 쓰는 것이 맞습니다.
  • 요즘이라면 Intl.NumberFormat, String.prototype.trim, <input type="email"> 같은 내장 기능으로 대부분 대체할 수 있습니다.

그래도 "필요한 것을 직접 만들어 보는 일"이 이 실험실의 출발점이었습니다.

💻 소스 보기

/**
 * <Don't Modify !!>
 * Name : _STJ.js (_SongToryJavascript.js)
 * Author : songtory
 * E-mail : [email protected]
 * Website : http://www.songtory.com
 * Date : 2015-04-02
 * Description : 자주 사용하는 함수모음
 */

var _STJ = {};

_STJ.info = {
    'ver': '1.0',
    'author':'songtory',
    'email':'[email protected]'
}


_STJ.ERROR = {
    'msgs': [
    ],
    'add': function (msg) {
        return this.error.msgs.push(msg);
    }
}


/**
 * Define the regular expressions that will be used
 */
var ruleRegex = /^(.+?)\[(.+)\]$/,
numericRegex = /^[0-9]+$/,
numericDashRegex = /^[\d\-\s]+$/,
integerRegex = /^\-?[0-9]+$/,
decimalRegex = /^\-?[0-9]*\.?[0-9]+$/,
emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
alphaRegex = /^[a-z]+$/i,
alphaNumericRegex = /^[a-z0-9]+$/i,
alphaDashRegex = /^[a-z0-9_\-]+$/i,
naturalRegex = /^[0-9]+$/i,
naturalNoZeroRegex = /^[1-9][0-9]*$/i,
ipRegex = /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/i,
base64Regex = /[^a-zA-Z0-9\/\+=]/i,
urlRegex = /^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;


/**
 * STRING관련 함수설정 
 */
_STJ.STRING = {
    'trim': function (str) {
       return str.replace(/^\s*/, "").replace(/\s*$/, "");
    },
    'nl2br': function (str) {
        return str.replace(/\n/g, '<br />');
    },
    'htmlspecialchars': function (str) {
        return str.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt').replace(/>/g, '&gt;');
    },
    'byteFormat': function (byteStr) {
        byteStr = parseInt(byteStr, 10);
        var r = '',
        u = '';
        if (byteStr >= 1099511627776)
        {
            r = Math.round(byteStr / 1099511627776)
            u = 'TB';
        }
        else if (byteStr >= 1073741824)
        {
            r = Math.round(byteStr / 1073741824)
            u = 'GB';
        } 
        else if (byteStr >= 1048576)
        {
            r = Math.round(byteStr / 1048576)
            u = 'MB';
        } 
        else if (byteStr >= 1024)
        {
            r = Math.round(byteStr / 1024)
            u = 'KB';
        } 
        else
        {
            r = Math.round(byteStr)
            u = 'Byte';
        }
        return r + ' ' + u;
    },
    'numberFormat': function (str) {
    	var reg = /(^[+-]?\d+)(\d{3})/;
	    str += '';
	    while (reg.test(str))
	        str = str.replace(reg, '$1' + ',' + '$2');	    
	    return str;
    }
}

/**
 *  이벤트(EVENT) 기능함수 설정
 */
_STJ.EVENT = {
	'show' : function(id) {
		var el = document.getElementById(id);
		el.style.display='block';
	},
	'hide' : function(id) {
		var el = document.getElementById(id);
		el.style.display='none';
	},
	'toggle': function (id) {
		var el = document.getElementById(id);
        if (el.style.display == 'none') {
            _STJ.EVENT.show(id);
        } else {
            _STJ.EVENT.hide(id);
        }
    }

}


/**
 *  브라우저관련 설정(종류,버전,모바일 체크)
 */
_STJ.browser = {
	'check' : function() {
		var agent = navigator.userAgent.toLowerCase();
		var v = '';

		if(agent.indexOf('chrome') > 0) return 'CR';
		if(agent.indexOf('safari') > 0) return 'SF';
		if(agent.indexOf('firefox') > 0) return 'FF';
		if(agent.indexOf('msie') > 0) return 'IE';
		if(agent.indexOf('rv:11') > 0) return 'IE11';

		return 'ETC';
	},
	'ieVer' : function() {
		var rv = -1; // -1 이면 11버전 이상
		var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");        
		var agent = navigator.userAgent;

		if (re.exec(agent) != null)
		{
			rv = parseFloat(RegExp.$1); 
		}            

		return rv;
	},
	'isMobile' : function(){
		var ismobile = (/iphone|ipod|blackberry|android|windows ce|lg|mot|samsung|sonyericsson/i.test(navigator.userAgent.toLowerCase()));
		return ismobile;
	}
	
}

/**
 *  쿠키(cookie) 설정
 */
_STJ.COOKIE = {
	'set' : function(name, value, expires) {
		var todayDate = new Date();

        todayDate.setDate( todayDate.getDate() + expires );
        document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"

        return true;
	},
	'get' : function(name) {
		var nameOfCookie = name + "=";
		var x = 0;
		
		while ( x <= document.cookie.length )
		{
			var y = (x+nameOfCookie.length);
			
			if ( document.cookie.substring( x, y ) == nameOfCookie )
			{
			
				if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
				{
					endOfCookie = document.cookie.length;
				}

				return unescape( document.cookie.substring( y, endOfCookie ) );
			
			}

			x = document.cookie.indexOf( " ", x ) + 1;
			
			if ( x == 0 )
			{
				break;	
			}
		}

		return "";
	},
	'del' : function(name) {
		var expireDate = new Date();

        expireDate.setDate( expireDate.getDate() - 1 );
        document.cookie = name + "= " + "; expires=" + expireDate.toGMTString() + "; path=/";

        return true;
	}
}


/**
 *  FORM 관련 함수
 */
_STJ.FORM = {

	'valid' : function(frm,field,rule,msg) {

		if(frm[field].length > 0) // 0보다 크면 radio or Checkbox 
		{
			var c = 0;
			for(i=0; i<frm[field].length; i++)
			{
				if(frm[field][i].checked)
				{
					c = c +1;
				}	
			}

			if(c !== Number(rule))
			{
				alert(msg + " 를(을) "+rule+ "개 체크해 주세요.");
				return false;
			}

			return true;
		}
		else
		{
			arrRule = rule.split("|");

			for(i=0; i < arrRule.length; i++)
			{
				if(arrRule[i] == 'require')
				{
					 if(!_STJ.validRule.require(frm[field].value))
					 {
					 	alert(msg+' 을(를) 입력하세요.');
					 	frm[field].focus();
					 	return false;
					 }	
				}
				else if(arrRule[i] == 'alpha')
				{
					if(!_STJ.validRule.alpha(frm[field].value))
					{
					 	alert(msg+' 은(는) 영문자만 입력이 가능합니다.');
					 	frm[field].focus();
					 	return false;
					}	
				}
				else if(arrRule[i] == 'number')
				{
					if(!_STJ.validRule.number(frm[field].value))
					{
					 	alert(msg+' 은(는) 숫자만 입력이 가능합니다.');
					 	frm[field].focus();
					 	return false;
					}	
				}
				else if(arrRule[i] == 'alphaNum')
				{
					if(!_STJ.validRule.alphaNum(frm[field].value))
					{
					 	alert(msg+' 은(는) (-,_)포함 영문자 와 숫자만 입력이 가능합니다.');
					 	frm[field].focus();
					 	return false;
					}	
				}
				else if(arrRule[i] == 'email')
				{
					if(!_STJ.validRule.email(frm[field].value))
					{
					 	alert(msg+' 은(는) 올바른 이메일 형식이 아닙니다.');
					 	frm[field].focus();
					 	return false;
					}	
				}	
				else if(arrRule[i] == 'url')
				{
					if(!_STJ.validRule.url(frm[field].value))
					{
					 	alert(msg+' 은(는) 올바른 URL 형식이 아닙니다.');
					 	frm[field].focus();
					 	return false;
					}	
				}
				else
				{
					alert('폼검증에 오류가 발생하였습니다.\n관리자에게 문의바랍니다. ');
					return false;
				}	
				
			}
		}

		return true;
	}
}


/**
 * validation Rule 설정 함수
 */
_STJ.validRule = {
	'require' : function(str) {
		return (str !== null && str !== '');	
	},
	'alpha' : function(str) {
		return (alphaRegex.test(str));
	},
	'number' : function(str) {
		return (numericRegex.test(str));
	},
	'alphaNum' : function(str) {
		return (alphaDashRegex.test(str));
	},
	'email' : function(str) {
		return (emailRegex.test(str));
	},
	'ip' : function(str) {
		return (ipRegex.test(str));
	},
	'url' : function(str) {
		return (urlRegex.test(str));
	},
	'base64' : function(str) {
		return (base64Regex.test(str));
	}

}

/**
 * Date 설정
 */

_STJ.DATE = {
	'format' : function(fmt) { //날짜포멧		
		var d = new Date();
		var r = "";

		r = fmt.replace('Y',d.getFullYear());
		r = r.replace('m',d.getMonth());
		r = r.replace('d',d.getDate());
		r = r.replace('h',d.getHours());
		r = r.replace('i',d.getMinutes());
		r = r.replace('s',d.getSeconds());

		return r;
	},
	'week' : function(date,lan) { //해당날짜의 요일
		if(lan == "KR")
		{
			var array_week = new Array('일','월','화','수','목','금','토');
		}
		else
		{
			var array_week = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
		}

		if(date == '' || typeof date == "undefined")
		{
			var d = new Date();
		}
		else
		{
			var arr_date = date.split('-');
			var d = new Date(arr_date[0],arr_date[1]-1,arr_date[2]);	
		}

		var w = d.getDay();

		return array_week[w];	
	},
	'd_day' : function(sdate,edate) {
		var arr_sdate = sdate.split("-");
		var arr_edate = edate.split("-");
		
		var s_date = new Date(arr_sdate[0],arr_sdate[1]-1,arr_sdate[2]);
		var e_date = new Date(arr_edate[0],arr_edate[1]-1,arr_edate[2]);

		var day = Math.floor((s_date-e_date)/86400000);
		
		return day;
	}
}


/**
 * window 팝업(새창)
 */
_STJ.popup = function(name,url,width,height,top,left,scroll) {

	var width 	= (width = "" || typeof scroll == 'undefined') ? 400 : width;
	var height 	= (height = "" || typeof scroll == 'undefined') ? 400 : height;
	var top 	= (top = "" || typeof scroll == 'undefined') ? 0 : top;
	var left 	= (left = "" || typeof scroll == 'undefined') ? 0 : left;
	var scroll 	= (scroll = "" || typeof scroll == 'undefined') ? "no" : scroll;
	
	window.open(url,name,"width="+width+",height="+height+",top="+top+",left="+left+"scrollbars="+scroll);

	return true;
}

📝 관련 킥노트 글