[jQuery] DatePicker 사용시 시작일 / 종료일 입력값 체크하기[jQuery] DatePicker 사용시 시작일 / 종료일 입력값 체크하기

Posted at 2018. 8. 20. 10:42 | Posted in JavaScript & jQuery/jQuery
반응형




■ 캘린더( DatePicker ) 사용시 시작일 / 종료일 예외처리




사이트 제작중 검색할 데이터의 시작일과 종료일을 설정하는 경우는 자주 있는 일이다.


그렇다면 검색 조건을 시작일이 종료일보다 이후에 오면 안되고,


종료일이 시작일보다 먼저일 수 없게 예외처리를 해두기 위해 스크립트를 짜게 되었고.


아래와 같이 정리해 두었다.



# 소스코드

<html>
<head>
<title>:: 시작일 / 종료일 체크하기 ::</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style type="text/css">
    .datePicker {
        text-align:center;
        width:80px;
    }

    ul {
        list-style:none;
        margin:0;
        padding:0;
    }

    li {
        margin: 0 0 0 0;
        padding: 0 0 0 0;
        border : 0;
        float: left;
    }
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
    jQuery(document).ready(function() {


        jQuery(".datePicker").datepicker();
        
        // jQuery UI Datepicker 한글 변환
        jQuery.datepicker.regional['ko'] = {
              closeText : "닫기"
            , prevText : ""
            , nextText : ""
            , currentText : "오늘"
            , monthNames : ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"]
            , monthNamesShort : ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"]
            , dayNames : ["일", "월", "화", "수", "목", "금", "토"]
            , dayNamesShort : ["일", "월", "화", "수", "목", "금", "토"]
            , dayNamesMin : ["일", "월", "화", "수", "목", "금", "토"]
            , weekHeader : "Wk"
            , dateFormat : "yy-mm-dd"
            , firstDay : 0
            , isRTL : false
            , yearSuffix : "&nbsp;년"
            , showMonthAfterYear : true
            , changeMonth : true
            // , changeYear : true
            // , autoSize : true

            , beforeShow:function(input) {
                var position = jQuery(input).position();
                setTimeout(function() {
                    jQuery("#ui-datepicker-div").css({"left":position.left});
               })
            }
        };
        jQuery.datepicker.setDefaults(jQuery.datepicker.regional['ko']);
    });


    function inputDateComparison(obj) {

        // 현재 엘리먼트의 부모(li) > 부모(ul) > 첫번째자식(li) > 첫번째자식(input)
        let startDate = inputDateSplit(obj.parentNode.parentNode.firstElementChild.firstChild.value);    // 시작일


        // 현재 엘리먼트의 부모(li) > 부모(ul) > 마지막자식(li) > 첫번째자식(input)

        let endDate = inputDateSplit(obj.parentNode.parentNode.lastElementChild.firstChild.value);        // 종료일

        let objDate = inputDateSplit(obj.value);    // 입력한 엘리먼트의 일자
        // 입력일을 확인하는 이유는 현재 작성한 일자가 시작일인지 종료일인지 확인하기 위해서이다.

        if(startDate == objDate && startDate > endDate) {
            alert("시작일이 종료일보다 이 후 일수는 없습니다.\n다시 선택하여 주시기 바랍니다.");
            obj.parentNode.parentNode.firstElementChild.firstChild.value = "";
            // obj.parentNode.parentNode.firstElementChild.firstChild.focus();
        }


        else if(endDate == objDate && endDate < startDate) {

            if(obj.parentNode.parentNode.firstElementChild.firstChild.value == "") {
                alert("시작일이 입력되지 않았습니다.\n시작일을 먼저 입력해주세요");
                obj.parentNode.parentNode.lastElementChild.firstChild.value = "";
                // obj.parentNode.parentNode.firstElementChild.firstChild.focus();
            }


            else {
                alert("종료일이 시작일보다 이 전 일수는 없습니다.\n다시 선택하여 주시기 바랍니다.");
                obj.parentNode.parentNode.lastElementChild.firstChild.value = "";
                // obj.parentNode.parentNode.lastElementChild.lastChild.focus();
            }
        }


        else {
            return false;
        }
    }


    // 날짜형식에 "-"이 사용된 경우에 한하여 날짜값에서 "-" 기호를 제거한다.
    function inputDateSplit(obj) {


        let dateArray = obj.split("-");
        return dateArray[0] + dateArray[1] + dateArray[2];
    }
</script>
</head>
<body>

   <ul>

        <li><input type="text" class="datePicker" onChange="inputDateComparison(this);" value=""/></li>
        <li>&nbsp;~&nbsp;</li>
        <li><input type="text" class="datePicker" onChange="inputDateComparison(this);" value=""/></li>

   </ul>

</body>
</html>




# 출력결과





반응형
//