Javascript: how to validate dates in format MM-DD-YYYY?
我在这里看到了一个潜在的答案,但那是YYYY-MM-DD:JavaScript日期验证
我为MM-DD-YYYY修改了上面的代码,但我还是无法让它工作:
1 2 3 4 5 6 7 8 9 10 | 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-YYYY,更好的是MM / DD / YYYY?
谢谢。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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')); |
有用。 (使用Firebug测试,因此使用console.log()。)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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; } |
这将检查每个月的有效天数和有效的闰年天数。
如何以"任何"日期格式验证日期?我一直在使用DateJS库并将其添加到现有表单中,以确保我获得有效的日期和时间。时间格式化我想要的方式。用户甚至可以输入"现在"和"明天"等内容,并将其转换为有效日期。
这是dateJS库:
http://www.datejs.com/
这是我写的jQuery技巧:
http://www.ssmedia.com/utilities/jquery/index.cfm/datejs.htm
我会使用Moment.js来完成这项任务。它使解析日期变得非常容易,并且还支持以正确的格式检测无效的date1。例如,考虑这个例子:
1 2 3 4 5 | 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) |
第一个
这可以用来简单地派生isValidDate方法:
1 2 3 4 | String.prototype.isValidDate = function() { var formats = ['MM-DD-YYYY', 'MM/DD/YYYY']; return moment("" + this, formats).isValid(); } |
1由于我可以找到关于这个问题的稀缺的小评论,我只会使用moment.js作为公历所涵盖的日期。可能有其他(包括历史或科学)日历的插件。
我使用这个正则表达式来验证MM-DD-YYYY:
1 2 3 4 5 6 7 | 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; } } |
它只匹配有效月份,你可以使用/ - 或。作为分隔符。
此功能将验证日期以查看它是否正确或是否采用正确的格式:DD / MM / YYYY。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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')); |
什么不起作用?这是经过测试的版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 |
简单的解决方法
1 2 3 4 5 | 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 | var matches = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/); |
或者,只需将参数更改为RegExp构造函数即可
1 | ^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$ |
将此函数传递给日期,格式为// 10-10-2012,id为object。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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] <= day) { if(b_date[1] <= month) { if(b_date[2] >= 1900 && b_date[2] <= todayDate.getFullYear()) { return true; } else { $("#"+id).val(''); alert('Please enter valid Year'); } } else { $("#"+id).val(''); alert('Please enter valid Month'); } } else { alert('Please enter valid Day'); $("#"+id).val(''); } } } |
这是为了验证formate中的日期字符串dd.mm.yyyy很容易定制它。你只需要在isValidDate()中调整pos1和pos2。
var dtCh ="。";
var minYear = 1900;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | 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 <= n; i++) { this[i] = 31; if (i==4 || i==6 || i==9 || i==11) { this[i] = 30; } if (i==2) { this[i] = 29; } } return this; } function isValidDate(dtStr){ var daysInMonth = DaysArray(12); var pos1=dtStr.indexOf(dtCh); var pos2=dtStr.indexOf(dtCh,pos1+1); var strDay=dtStr.substring(0,pos1); var strMonth=dtStr.substring(pos1+1,pos2); var strYear=dtStr.substring(pos2+1); strYr=strYear; if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1); if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1); for (var i = 1; i <= 3; i++) { if (strYr.charAt(0)=="0" && strYr.length>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<1 || month<1 || month>12){ alert("Please enter a valid month"); return false; } if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){ alert("Please enter a valid day"); return false; } if (strYear.length != 4 || year==0 || year<minYear){ alert("Please enter a valid 4 digit year after"+minYear); return false; } if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){ alert("Please enter a valid date"); return false; } return true; } |
德国变种,但可以适应Iso
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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 } |
1 2 3 4 | 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 "); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | <!DOCTYPE html> <html> <head> 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 <= '57')) || (charCode == '47')) { return true; } else { return false; } } </head> <body> <form name="myForm" action="#"> <table> <tr> <td>Enter Date</td> <td><input type="text" onkeypress="return restrictCharacters(event);" name="dateInput"/></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> </form> </body> </html> |
请在下面的代码中找到,该代码可以对任何提供的格式执行日期验证,或者根据用户区域设置来验证开始日期和结束日期。可能有一些更好的方法,但已经提出了这个。已经测试过以下格式:MM / dd / yyyy,dd / MM / yyyy,yyyy-MM-dd,yyyy.MM.dd,yyyy / MM / dd和dd-MM-yyyy。
注意提供的日期格式和日期字符串齐头并进。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | <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; } |
Below is the HTML snippet
1 2 3 4 5 | <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');" /> |
如果您的日期需要匹配DD.MM.YYYY并使用AngularJS,请使用以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $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')); |
有关范围对象的更多信息,请参见此处。没有AngularJS,只需将第一行更改为:
1 | ValidDate = new function(value) { |
并使用以下方式调用:
1 | var MyDate= ValidDate('29.09.2016'); |
DateFormat = DD.MM.YYYY或D.M.YYYY
1 2 3 4 5 6 7 | 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';} } |
试试这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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; } } |
短而快
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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')); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | <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 <= n; i++) { this[i] = 31 if (i==4 || i==6 || i==9 || i==11) {this[i] = 30} if (i==2) {this[i] = 29} } return this } function isDate(dtStr){ var daysInMonth = DaysArray(12) var pos1=dtStr.indexOf(dtCh) var pos2=dtStr.indexOf(dtCh,pos1+1) var strDay=dtStr.substring(0,pos1) var strMonth=dtStr.substring(pos1+1,pos2) var strYear=dtStr.substring(pos2+1) strYr=strYear if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1) if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1) for (var i = 1; i <= 3; i++) { if (strYr.charAt(0)=="0" && strYr.length>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<1 || month<1 || month>12){ alert("Please enter a valid month") return false } if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){ alert("Please enter a valid day") return false } if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){ 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 } |