Javascript: 날짜 형식으로 검증하는 방법을 mm dd yy?

내가 여기 년-월-일 대한 답변을 것도 봤다. JavaScript 날짜 검증

그래서 내가 수정한 mm dd yy can& # 39 위, 그래도 같은 코드 코드 이해했소 사용할 수 없다.

String.prototype.isValidDate = function() 
{
     var IsoDateRe = new RegExp("^([0-9]{2})-([0-9]{2})-([0-9]{4})$");
     var matches = IsoDateRe.exec(this);
     if (!matches) return false;
     var composedDate = new Date(matches[3], (matches[1] - 1), matches[2]);
     return ((composedDate.getMonth() == (matches[1] - 1)) &&
      (composedDate.getDate() == matches[2]) &&
      (composedDate.getFullYear() == matches[3]));
}

위의 코드는 위해 일할 수 있는 방법은 저도 MM / DD yy / mm dd yy 및 더 좋은 것은?

감사합니다.

질문에 대한 의견 (2)
function isValidDate(date)
{
    var matches = /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/.exec(date);
    if (matches == null) return false;
    var d = matches[2];
    var m = matches[1] - 1;
    var y = matches[3];
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
            composedDate.getMonth() == m &&
            composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-1961'));
console.log(isValidDate('12/11/1961'));
console.log(isValidDate('02-11-1961'));
console.log(isValidDate('12/01/1961'));
console.log(isValidDate('13-11-1961'));
console.log(isValidDate('11-31-1961'));
console.log(isValidDate('11-31-1061'));

작동하잖아. ((), 즉 콘솔드로그 방화범 테스트했습니다.)

해설 (5)
function isValidDate(date) {
        var valid = true;

        date = date.replace('/-/g', '');

        var month = parseInt(date.substring(0, 2),10);
        var day   = parseInt(date.substring(2, 4),10);
        var year  = parseInt(date.substring(4, 8),10);

        if(isNaN(month) || isNaN(day) || isNaN(year)) return false;

        if((month < 1) || (month > 12)) valid = false;
        else if((day < 1) || (day > 31)) valid = false;
        else if(((month == 4) || (month == 6) || (month == 9) || (month == 11)) && (day > 30)) valid = false;
        else if((month == 2) && (((year % 400) == 0) || ((year % 4) == 0)) && ((year % 100) != 0) && (day > 29)) valid = false;
        else if((month == 2) && ((year % 100) == 0) && (day > 29)) valid = false;
        else if((month == 2) && (day > 28)) valid = false;

    return valid;
}

유효성 검사 (일) 이 매달, 유효한 윤년 일입니다.

해설 (7)

어때, 내 검증중 날짜를 &quot ANY&quot. 날짜 형식? # 39, ve been i& 다테이스 사용하여 라이브러리 및 추가할 수 있도록 기존 양식을 저도 유효함 날짜 &amp. 배 운행에서어떠한 포맷됩니다 내가 바라는 건. 심지어 &quot 입력하십시오. 행동한다면, now&quot 수 있습니다. 및 &quot tomorrow"; 또 변환될지 유효한 바뀌었다.

S # 39, here& 다테이스 라이브러리: http://www.datejs.com/

s # 39, 이는 내가 jQuery 팁 및 here& 다음과 같이 썼다. http://www.ssmedia.com/utilities/jquery/index.cfm/datejs.htm

해설 (1)

꼭 이래야겠어요 경로재설정 [모멘t.j스] (http://momentjs.com/) 이 작업. 이 때문에 매우 쉽게 분석할 수 날짜 및 뿐만 아니라, 잘못된 date&lt sup&gt 1&lt /sup&gt 지원부에서는 감지할 수 있습니다.;; 올바른 형식이. 예를 들어, 고려해보십시오 [이 예] (http://jsfiddle.net/ygqgz/):

var formats = ['MM-DD-YYYY', 'MM/DD/YYYY']

moment('11/28/1981', formats).isValid()  // true
moment('2-29-2003', formats).isValid()   // false (not leap year)
moment('2-29-2004', formats).isValid()   // true  (leap year)

첫 번째 '모멘트 (., 포맷용)' 를 사용하여 구문 입력 관찰지역 형식에 따라 취소되었다. 그 결과 지금 우리는 '에서' 이바리드 함수가 호출될 수 있도록 객체에는 떠날려하면 경우 실제로 유효함 날짜 및.

이 방법을 파생합니다 이바리다트 사소 데 사용될 수 있습니다.

String.prototype.isValidDate = function() {
    var formats = ['MM-DD-YYYY', 'MM/DD/YYYY'];
    return moment("" + this, formats).isValid();
}

&lt sup&gt 1&lt /sup>;;; As I 찾을 수 있는 이 문제에 대한 해설, 내가 부족한 리틀이에요 사용해야 모멘t.j스 날짜에 적용을 받는 [그레고리력] (http://en.wikipedia.org/wiki/Gregorian_calendar). 캘린더 (또는 과학 역사 등) 다른 플러그인을 있을 수 있습니다.

해설 (0)

내가 이 regex 를 검증하는 mm dd yy:

function isValidDate(subject){
  if (subject.match(/^(?:(0[1-9]|1[012])[\- \/.](0[1-9]|[12][0-9]|3[01])[\- \/.](19|20)[0-9]{2})$/)){
    return true;
  }else{
    return false;
  }
}

It / -또는 명에만 유효함 개월 사용할 수 있습니다. 구분 있다.

해설 (4)

이 기능은 검증하십시오 it& # 39 의 경우 정확한 날짜 수 있는지, 또는 it& # 39 의 적절한 형식은 다음과 같다. DD/MM/YYYY.

function isValidDate(date)
{
    var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
    if (matches == null) return false;
    var d = matches[1];
    var m = matches[2]-1;
    var y = matches[3];
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
           composedDate.getMonth() == m &&
           composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-1961'));
console.log(isValidDate('12/11/1961'));
console.log(isValidDate('02-11-1961'));
console.log(isValidDate('12/01/1961'));
console.log(isValidDate('13-11-1961'));
console.log(isValidDate('11-31-1961'));
console.log(isValidDate('11-31-1061'));
해설 (0)

이에 대해 어떤 isn& # 39, t apc®? # 39 의 here& 테스트 버전:

String.prototype.isValidDate = function()   {

    var match   =   this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
    var test    =   new Date(match[3], match[1] - 1, match[2]);
    return (
        (test.getMonth() == match[1] - 1) &&
        (test.getDate() == match[2]) &&
        (test.getFullYear() == match[3])
    );
}

var date = '12/08/1984'; // Date() is 'Sat Dec 08 1984 00:00:00 GMT-0800 (PST)'
alert(date.isValidDate() ); // true
해설 (0)

정보기술 (it) 이 처음 두 줄의 기능이 다소 변경하여 단순화할 수 있습니다.

var matches = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);

또는, 그냥 변경하십시오 구성자를 스크램블된 매개 변수를 정규 표현식

^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$
해설 (0)

간단한 방법은 pardiso

var day = document.getElementById("DayTextBox").value;

var regExp = /^([1-9]|[1][012])\/|-([1-9]|[1][0-9]|[2][0-9]|[3][01])\/|-([1][6-9][0-9][0-9]|[2][0][01][0-9])$/;

return regExp.test(day);
해설 (1)

그러나 독일 변형, Iso 적응됩니까 될 수 있습니다.

export function isLeapYear(year) {
  return (
    year % 4 === 0 && (year % 100 != 0 || year % 1000 === 0 || year % 400 === 0)
  )
}

export function isValidGermanDate(germanDate) {
  if (
    !germanDate ||
    germanDate.length < 5 ||
    germanDate.split('.').length < 3
  ) {
    return false
  }

  const day = parseInt(germanDate.split('.')[0])
  const month = parseInt(germanDate.split('.')[1])
  const year = parseInt(germanDate.split('.')[2])

  if (isNaN(month) || isNaN(day) || isNaN(year)) {
    return false
  }

  if (month < 1 || month > 12) {
    return false
  }

  if (day < 1 || day > 31) {
    return false
  }

  if ((month === 4 || month === 6 || month === 9 || month === 11) && day > 30) {
    return false
  }

  if (isLeapYear(year)) {
    if (month === 2 && day > 29) {
      return false
    }
  } else {
    if (month === 2 && day > 28) {
      return false
    }
  }

  return true
}
해설 (0)

이 이온 dd. mm. yyyy 쉽게 에서 문자열을 날짜 검증중 캐비닛용입니다 사용자정의하려면 거잖나. 방금 조정해야 하는 pos1 및 pos2 이바리다트 () 에서.

var 드치 = &quot .";; var 미니어 = 1900년;


function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
    for (var i = 1; i 1) 
        strDay=strDay.substring(1);
    if (strMonth.charAt(0)=="0" && strMonth.length>1) 
        strMonth=strMonth.substring(1);
    for (var i = 1; i 1) 
            strYr=strYr.substring(1);
    }
    month=parseInt(strMonth);
    day=parseInt(strDay);
    year=parseInt(strYr);
    if (pos1==-1 || pos2==-1){
        alert("The date format should be : dd.mm.yyyy");
        return false;
    }
    if (strMonth.length daysInMonth[month]){
        alert("Please enter a valid day");
        return false;
    }
    if (strYear.length != 4 || year==0 || year
해설 (0)

이 기능을 전달하십시오 날짜 형식으로 //10- 10-2012 과 id 개체입니다.


function isValidDateFormat(date, id)
{
  var todayDate = new Date();
  var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);

  if (matches == null)
  {
   if(date != '__-__-____')
    {
      alert('Please enter valid date');
    }
  }
  else
  {
    var day    = 31;
    var month  = 12;
    var b_date = date.split("-");
    if(b_date[0] 
해설 (1)
if (document.getElementById('expiryDay').value != test(match("/^([0-9]{2})\/([0-9]{2})$/"))){
     alert("Enter the date in two digit month flowed by two digits year \n");
}
해설 (0)





 <script>
     function dateCheck(inputText) {
         debugger;

         var dateFormat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;

         var flag = 1;

         if (inputText.value.match(dateFormat)) {
             document.myForm.dateInput.focus();

             var inputFormat1 = inputText.value.split('/');
             var inputFormat2 = inputText.value.split('-');
             linputFormat1 = inputFormat1.length;
             linputFormat2 = inputFormat2.length;

             if (linputFormat1 > 1) {
                 var pdate = inputText.value.split('/');
             }
             else if (linputFormat2 > 1) {
                 var pdate = inputText.value.split('-');
             }
             var date = parseInt(pdate[0]);
             var month = parseInt(pdate[1]);
             var year = parseInt(pdate[2]);

             var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
             if (month == 1 || month > 2) {
                 if (date > ListofDays[month - 1]) {
                     alert("Invalid date format!");
                     return false;
                 }
             }

             if (month == 2) {
                 var leapYear = false;

                 if ((!(year % 4) && year % 100) || !(year % 400)) {
                     leapYear = true;

                 }
                 if ((leapYear == false) && (date >= 29)) {
                     alert("Invalid date format!");
                     return false;
                 }
                 if ((leapYear == true) && (date > 29)) {
                     alert("Invalid date format!");
                     return false;
                 }
             }
             if (flag == 1) {
                 alert("Valid Date");
             }
         }
         else {
             alert("Invalid date format!");
             document.myForm.dateInput.focus();
             return false;
         }
     }
     function restrictCharacters(evt) {

         evt = (evt) ? evt : window.event;
         var charCode = (evt.which) ? evt.which : evt.keyCode;
         if (((charCode >= '48') && (charCode </td>
                    <td></td>
                    <td><span id="span2"></span></td>
                </tr>

                <tr>
                    <td></td>
                    <td><input type="button" name="submit" value="Submit" onclick="dateCheck(document.myForm.dateInput)"  /></td>
                </tr>
            </table>

    </div>   

해설 (1)

아래 코드를 실행할 수 있는 모든 날짜 검증 부탁일세 에 제공된 형식 또는 날짜 / to / from 검증하기 위해, 최종 사용자에 따라 로케일에 시작. 더 나은 방법이 있을 수 있지만 일부 내놓아야 이. 테스트한 위한 it 형식식 다음과 같습니다. MM/dd/yyyy, / MM / dd yy, 년-월-일, yyyy. 마스 / MM / dd, dd yy 및 dd yy mm.

  • 참고 제공한 날짜 형식 및 날짜 문자열이어야 손에 hand.* 검색하기를
<script type="text/javascript">
function validate(format) {

    if(isAfterCurrentDate(document.getElementById('start').value, format)) {
        alert('Date is after the current date.');
    } else {
        alert('Date is not after the current date.');
    }
    if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
        alert('Date is before current date.');
    } else {
        alert('Date is not before current date.');
    }
    if(isCurrentDate(document.getElementById('start').value, format)) {
        alert('Date is current date.');
    } else {
        alert('Date is not a current date.');
    }
    if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
        alert('Start/Effective Date cannot be greater than End/Expiration Date');
    } else {
        alert('Valid dates...');
    }
    if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
        alert('End/Expiration Date cannot be less than Start/Effective Date');
    } else {
        alert('Valid dates...');
    }
    if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
        alert('Dates are equals...');
    } else {
        alert('Dates are not equals...');
    }
    if (isDate(document.getElementById('start').value, format)) {
        alert('Is valid date...');
    } else {
        alert('Is invalid date...');
    }
}

/**
 * This method gets the year index from the supplied format
 */
function getYearIndex(format) {

    var tokens = splitDateFormat(format);

    if (tokens[0] === 'YYYY'
            || tokens[0] === 'yyyy') {
        return 0;
    } else if (tokens[1]=== 'YYYY'
            || tokens[1] === 'yyyy') {
        return 1;
    } else if (tokens[2] === 'YYYY'
            || tokens[2] === 'yyyy') {
        return 2;
    }
    // Returning the default value as -1
    return -1;
}

/**
 * This method returns the year string located at the supplied index
 */
function getYear(date, index) {

    var tokens = splitDateFormat(date);
    return tokens[index];
}

/**
 * This method gets the month index from the supplied format
 */
function getMonthIndex(format) {

    var tokens = splitDateFormat(format);

    if (tokens[0] === 'MM'
            || tokens[0] === 'mm') {
        return 0;
    } else if (tokens[1] === 'MM'
            || tokens[1] === 'mm') {
        return 1;
    } else if (tokens[2] === 'MM'
            || tokens[2] === 'mm') {
        return 2;
    }
    // Returning the default value as -1
    return -1;
}

/**
 * This method returns the month string located at the supplied index
 */
function getMonth(date, index) {

    var tokens = splitDateFormat(date);
    return tokens[index];
}

/**
 * This method gets the date index from the supplied format
 */
function getDateIndex(format) {

    var tokens = splitDateFormat(format);

    if (tokens[0] === 'DD'
            || tokens[0] === 'dd') {
        return 0;
    } else if (tokens[1] === 'DD'
            || tokens[1] === 'dd') {
        return 1;
    } else if (tokens[2] === 'DD'
            || tokens[2] === 'dd') {
        return 2;
    }
    // Returning the default value as -1
    return -1;
}

/**
 * This method returns the date string located at the supplied index
 */
function getDate(date, index) {

    var tokens = splitDateFormat(date);
    return tokens[index];
}

/**
 * This method returns true if date1 is before date2 else return false
 */
function isBefore(date1, date2, format) {
    // Validating if date1 date is greater than the date2 date
    if (new Date(getYear(date1, getYearIndex(format)), 
            getMonth(date1, getMonthIndex(format)) - 1, 
            getDate(date1, getDateIndex(format))).getTime()
        > new Date(getYear(date2, getYearIndex(format)), 
            getMonth(date2, getMonthIndex(format)) - 1, 
            getDate(date2, getDateIndex(format))).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method returns true if date1 is after date2 else return false
 */
function isAfter(date1, date2, format) {
    // Validating if date2 date is less than the date1 date
    if (new Date(getYear(date2, getYearIndex(format)), 
            getMonth(date2, getMonthIndex(format)) - 1, 
            getDate(date2, getDateIndex(format))).getTime()
        < new Date(getYear(date1, getYearIndex(format)), 
            getMonth(date1, getMonthIndex(format)) - 1, 
            getDate(date1, getDateIndex(format))).getTime()
        ) {
        return true;
    } 
    return false;                
}

/**
 * This method returns true if date1 is equals to date2 else return false
 */
function isEquals(date1, date2, format) {
    // Validating if date1 date is equals to the date2 date
    if (new Date(getYear(date1, getYearIndex(format)), 
            getMonth(date1, getMonthIndex(format)) - 1, 
            getDate(date1, getDateIndex(format))).getTime()
        === new Date(getYear(date2, getYearIndex(format)), 
            getMonth(date2, getMonthIndex(format)) - 1, 
            getDate(date2, getDateIndex(format))).getTime()) {
        return true;
    } 
    return false;
}

/**
 * This method validates and returns true if the supplied date is 
 * equals to the current date.
 */
function isCurrentDate(date, format) {
    // Validating if the supplied date is the current date
    if (new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))).getTime()
        === new Date(new Date().getFullYear(), 
                new Date().getMonth(), 
                new Date().getDate()).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method validates and returns true if the supplied date value 
 * is before the current date.
 */
function isBeforeCurrentDate(date, format) {
    // Validating if the supplied date is before the current date
    if (new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))).getTime()
        < new Date(new Date().getFullYear(), 
                new Date().getMonth(), 
                new Date().getDate()).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method validates and returns true if the supplied date value 
 * is after the current date.
 */
function isAfterCurrentDate(date, format) {
    // Validating if the supplied date is before the current date
    if (new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))).getTime()
        > new Date(new Date().getFullYear(),
                new Date().getMonth(), 
                new Date().getDate()).getTime()) {
        return true;
    } 
    return false;                
}

/**
 * This method splits the supplied date OR format based 
 * on non alpha numeric characters in the supplied string.
 */
function splitDateFormat(dateFormat) {
    // Spliting the supplied string based on non characters
    return dateFormat.split(/\W/);
}

/*
 * This method validates if the supplied value is a valid date.
 */
function isDate(date, format) {                
    // Validating if the supplied date string is valid and not a NaN (Not a Number)
    if (!isNaN(new Date(getYear(date, getYearIndex(format)), 
            getMonth(date, getMonthIndex(format)) - 1, 
            getDate(date, getDateIndex(format))))) {                    
        return true;
    } 
    return false;                                      
}

&lt /script>;

&gt. 다음은 HTML 스니핏

    <input type="text" name="start" id="start" size="10" value="05/31/2016" />
<br/> 
<input type="text" name="end" id="end" size="10" value="04/28/2016" />
<br/>
<input type="button" value="Submit" onclick="javascript:validate('MM/dd/yyyy');" />
해설 (0)

날짜 요구사항뿐 앙굴라이스 일치시키려면 dd. mm. yyyy 및 사용할 경우, 다음 코드를 사용합니다.

$scope.validDate = function(value){
            var matches = /^(\d{1,2})[.](\d{1,2})[.](\d{4})$/.exec(value);
            if (matches == null) return false;
            var d = matches[1];
            var m = matches[2] - 1;
            var y = matches[3];
            var composedDate = new Date(y, m, d);
            return composedDate.getDate() == d &&
                composedDate.getMonth() == m &&
                composedDate.getFullYear() == y;
        };
            console.log($scope.validDate('22.04.2001'));
            console.log($scope.validDate('03.10.2001'));
            console.log($scope.validDate('30.02.2001'));
            console.log($scope.validDate('23.09.2016'));
            console.log($scope.validDate('29.02.2016'));
            console.log($scope.validDate('31.02.2016'));

더 범위에 대한 객체에는 korea. [here] (https://docs.angularjs.org/guide/scope). 첫 선을 변경하십시오 앙굴라이스 없이 됩니다.

ValidDate = new function(value) {

정보기술 (it) 및 전화 사용:

var MyDate= ValidDate('29.09.2016');
해설 (3)

마리야야 다테포르마 = dd. mm. yyyy 또는 D.

function dateValidate(val){ 
var dateStr = val.split('.'); 
  var date = new Date(dateStr[2], dateStr[1]-1, dateStr[0]); 
  if(date.getDate() == dateStr[0] && date.getMonth()+1 == dateStr[1] && date.getFullYear() == dateStr[2])
  { return date; }
  else{ return 'NotValid';} 
}
해설 (0)

이거 드세요.

function validateDate(dates){
    re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;     
    var days=new Array(31,28,31,30,31,30,31,31,30,31,30,31);

            if(regs = dates.match(re)) {
                    // day value between 1 and 31
                    if(regs[1] < 1 || regs[1] > 31) {                  
                      return false;
                    }
                    // month value between 1 and 12
                    if(regs[2] < 1 || regs[2] > 12) {                       
                      return false;
                    }

                    var maxday=days[regs[2]-1];

                    if(regs[2]==2){
                        if(regs[3]%4==0){
                            maxday=maxday+1;                                
                        }
                    }

                    if(regs[1]>maxday){
                        return false;
                    }

                    return true;
              }else{
                  return false;
              }                   
}
해설 (0)

짧고 빠른.

<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. &gt 거짓값 -;

function dateValid(date) {
  var match = date.match(/^(\d\d)-(\d\d)-(\d{4})$/) || [];
  var m = (match[1] | 0) - 1;
  var d = match[2] | 0;
  var y = match[3] | 0;
  return !(
      m < 0 ||                     // Before January
      m > 11 ||                    // After December
      d < 1 ||                     // Before the 1st of the month
      d - 30 > (2741 >> m & 1) ||  // After the 30th or 31st of the month using bitmap
      m == 1 && d - 28 >           // After the 28th or 29th of February depending on leap year
          (!(y % 4) && y % 100 || !(y % 400)));
}

console.log('02-29-2000', dateValid('02-29-2000'));
console.log('02-29-2001', dateValid('02-29-2001'));
console.log('12-31-1970', dateValid('12-31-1970'));
console.log('Hello', dateValid('Hello'));

끝 - &lt 스니핏 >;!

해설 (2)
<script language = "Javascript">
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
    for (var i = 1; i 1) strDay=strDay.substring(1)
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
    for (var i = 1; i 1) strYr=strYr.substring(1)
    }
    month=parseInt(strMonth)
    day=parseInt(strDay)
    year=parseInt(strYr)
    if (pos1==-1 || pos2==-1){
        alert("The date format should be : dd/mm/yyyy")
        return false
    }
    if (strMonth.length daysInMonth[month]){
        alert("Please enter a valid day")
        return false
    }
    if (strYear.length != 4 || year==0 || yearmaxYear){
        alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
        return false
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
        alert("Please enter a valid date")
        return false
    }
return true
}

function ValidateForm(){
    var dt=document.frmSample.txtDateenter code here
    if (isDate(dt.value)==false){
        dt.focus()
        return false
    }
    return true
 }

</script>
해설 (0)