본문 바로가기

[Program]/[Html & Javascript]

스크립트 날짜에 하이픈 자동넣기

날짜에 자동으로 하이픈 넣어주는 소스입니다.

 

2000-00-00 형태로 자동으로 변환해줍니다

 

날짜에 - 넣기 날짜에 하이픈 넣기 스크립트소스

 

function assist(event){
var time = new Date()
  , y = String(time.getFullYear())
  , m = time.getMonth()
  , d = time.getDate()
  , h = '-'
  , lists = {

    keyup : [
 // 숫자, - 외 제거
  [/[^\d\-]/, '']
 // 0000 > 00-00
 , [/^(\d\d)(\d\d)$/, '$1-$2']
 // 00-000 > 00-00-0
 , [/^(\d\d\-\d\d)(\d+)$/, '$1-$2']
 // 00-00-000 > 0000-00-0
 , [/^(\d\d)-(\d\d)-(\d\d)(\d+)$/, '$1$2-$3-$4']
 // 00-00-0-0 > 0000-0-0
 , [/^(\d\d)-(\d\d)-(\d\d?)(-\d+)$/, '$1$2-$3$4']
 // 0000-0000 > 0000-00-00
 , [/^(\d{4}-\d\d)(\d\d)$/, '$1-$2']
 // 00000000 > 0000-00-00
 , [/^(\d{4})(\d\d)(\d\d)$/, '$1-$2-$3']
 // 이탈 제거
 , [/(\d{4}-\d\d?-\d\d).+/, '$1']
 ]
 , blur : [
   // 날짜만 있을 때 월 붙이기
 [/^(0?[1-9]|[1-2][0-9]|3[0-1])$/, m+'-$1', 1]
 // 월-날짜 만 있을 때 연도 붙이기
 , [/^(0?[1-9]|1[0-2])\-?(0[1-9]|[1-2][0-9]|3[01])$/, y+'-$1-$2']
 , [/^((?:0m?[1-9]|1[0-2])\-[1-9])$/, y+'-$1']
 // 연도 4 자리로
 , [/^(\d\-\d\d?\-\d\d?)$/, y.substr(0, 3)+'$1', 1]
 , [/^(\d\d\-\d\d?\-\d\d?)$/, y.substr(0, 2)+'$1', 1]
 // 0 자리 붙이기
 , [/(\d{4}-)(\d-\d\d?)$/, '$10$2', 1]
 , [/(\d{4}-\d\d-)(\d)$/, '$10$2']
 ]
}

event = event || window.event;

var input = event.target || event.srcElement
  , value = input.value
  , list = lists[event.type]
  ;

  for(var i=0, c=list.length, match; i<c; i++){

match = list[i];

if(match[0].test(value)){


input.value = value.replace(match[0], match[1]);


if(!match[2])


    break;

}
}  }

 

<input type="text" name="birth" onkeyup="assist();" onblur="assist();" / >