[英]javascript date validation using date object
According to http://www.codingforums.com/archive/index.php/t-98569.html , the date validation could be done using the javascript's date object. 根据http://www.codingforums.com/archive/index.php/t-98569.html ,可以使用javascript的日期对象完成日期验证。
I've a similar scenario, where I have individual year,month,date in seperate text boxes which get validated by regular expressions.Now I would like to leverage the JS's date object to check stuff like days in a month and leap year validation which are not done by RegExp validation. 我有一个类似的场景,我有单独的年,月,日期在单独的文本框中,通过正则表达式验证。现在我想利用JS的日期对象来检查像一个月的日子和闰年验证这样的东西不是通过RegExp验证完成的。 But the stuff discussed in the above link doesn't quite work for me. 但上面链接中讨论的内容对我来说并不适用。 For example, 例如,
<script type="text/javascript">
var dy= new Date(2001,2,30);
alert(dy.getFullYear()+" "+dy.getMonth()+" "+dy.getDate());
</script>
returns the date as it is. 按原样返回日期。 Shouldn't dy.getMonth() return something like -1 to show that 30 days doesn't exist in the month of February?. 难道dy.getMonth()不应该返回-1这样的东西来表明2月份不存在30天吗? If this isn't possible using Date object, please suggest some alternatives to validate the date. 如果使用Date对象无法做到这一点,请提供一些替代方法来验证日期。
Update: I just found another link(http://internotredici.com/article/checkdateinjavascript/) which says the same. 更新:我刚刚发现了另一个链接(http://internotredici.com/article/checkdateinjavascript/)。 PS:I am working on JS1.2 which is pretty old. PS:我正在研究JS1.2,它已经很老了。
You can make the date from the day, month, year bits, and then check that the bits are correct. 您可以从日,月,年位开始生成日期,然后检查这些位是否正确。
function isvalid_mdy(s){
var day, A= s.split(/\D+/).map(function(itm,i){return parseInt(itm,10)});
A[0]-=1;
try{
day= new Date(A[2], A[0], A[1]);
if(day.getMonth()== A[0] && day.getDate()== A[1]) return day;
throw new Error('Bad Date ');
}
catch(er){
return er.message;
}
}
function isvalid_dmy(s){
var day, A= s.split(/\D+/).map(function(itm,i){return parseInt(itm,10)});
A[1]-=1;
try{
day= new Date(A[2], A[1], A[0]);
if(day.getMonth()== A[1] && day.getDate()== A[0]) return day;
throw new Error('Bad Date ');
}
catch(er){
return er.message;
}
}
This may help some one. 这可能对某人有所帮助。 Have written some methods which will get perform the date validations. 编写了一些可以执行日期验证的方法。 There could be some better ways but I have come up with these. 可能有一些更好的方法,但我想出了这些。 This help in validating the dates on locale based formats. 这有助于验证基于语言环境的格式的日期。 NOTE: date format and date string as provided in the input fields go hand in hand. 注意:输入字段中提供的日期格式和日期字符串齐头并进。
<script type="text/javascript">
function validate() {
var format = 'yyyy-MM-dd';
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;
}
</script>
HTML date associated input fields HTML日期关联的输入字段
<input type="text" name="start" id="start" size="10" value="" />
<br/>
<input type="text" name="end" id="end" size="10" value="" />
<br/>
<input type="button" value="Submit" onclick="javascript:validate();" />
In JS, monht starts by 0, so 0=Jan,1=Feb,2=Mar 在JS中,monht从0开始,因此0 = Jan,1 = Feb,2 = Mar
30,1 (30 FEB) will be 2 Mar 30,1(30 FEB)将于3月2日
You will have to test this by yourself.. 你必须自己测试一下..
This can help you - validate-date 这可以帮助您 - 验证日期
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.