JAVASCRIPT datetime validation 하는 방법


# 가장 간단한 방법 (Date.parse 이용)

IsValidDate = Date.parse("2020-05-01")

if (isNAN(IsValidDate)){
    alert("not a date")
}

참고 : [Date.parse() - JavaScript | MDN](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Date/parse)

참고 : [꿀벌개발일지 :: Date.parse() 가 지원하는 날짜 포맷](https://ohgyun.com/540)

 

# moment js 사용

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment-with-locales.min.js"></script>

valid_from_date = moment(from_date, "YYYY-MM-DD HH:mm:ss", true).isValid();

 

참고 : [Moment.js | Docs](https://momentjs.com/docs/#/parsing/string/)

참고 : [momentjs - Is there a way to validate time using Moment JS? - Stack Overflow](https://stackoverflow.com/questions/26040397/is-there-a-way-to-validate-time-using-moment-js)

 

# datepicker.parseDate 이용

function validateDate(dateField) {
       try{
           $.datepicker.parseDate('mm/y', dateField, null);
       }
       catch(error){
           alert(error);
       }
}

  

참고 : [datepicker.parseDate - jQuery Forum](https://forum.jquery.com/topic/datepicker-parsedate)

참고 : [validation - How to validate date with format "mm/dd/yyyy" in JavaScript? - Stack Overflow](https://stackoverflow.com/questions/6177975/how-to-validate-date-with-format-mm-dd-yyyy-in-javascript)

 

# 시간 체크하는 함수 사용

function isDatetime(d) {
    var re = /[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) (2[0-3]|[01][0-9]):[0-5][0-9]/;
    //         yyyy -       MM      -       dd           hh     :   mm  :   ss
  return re.test(d);
}


if (!isDatetime("2020-05-01 11:00:00")){
    alert('시간 형태가 잘못되었습니다.')
}

 

참고 : [[Javascript] 문자로 된 날짜(Datetime) 유효성 검사 (yyyy-mm-dd hh:ii:ss) :: 확장형 뇌 저장소](https://extbrain.tistory.com/33)

 

+ Recent posts