How can I determine whether a given string represents a date?
I开发者_JS百科s there an isDate
function in jQuery?
It should return true
if the input is a date, and false
otherwise.
If you don't want to deal with external libraries, a simple javascript-only solution is:
function isDate(val) {
var d = new Date(val);
return !isNaN(d.valueOf());
}
UPDATE: !!Major Caveat!!
@BarryPicker raises a good point in the comments. JavaScript silently converts February 29 to March 1 for all non-leap years. This behavior appears to be limited strictly to days through 31 (e.g., March 32 is not converted to April 1, but June 31 is converted to July 1). Depending on your situation, this may be a limitation you can accept, but you should be aware of it:
>>> new Date('2/29/2014')
Sat Mar 01 2014 00:00:00 GMT-0500 (Eastern Standard Time)
>>> new Date('3/32/2014')
Invalid Date
>>> new Date('2/29/2015')
Sun Mar 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)
>>> isDate('2/29/2014')
true // <-- no it's not true! 2/29/2014 is not a valid date!
>>> isDate('6/31/2015')
true // <-- not true again! Apparently, the crux of the problem is that it
// allows the day count to reach "31" regardless of the month..
simplest way in javascript is:
function isDate(dateVal) {
var d = new Date(dateVal);
return d.toString() === 'Invalid Date'? false: true;
}
Depending on how you're trying to implement this, you may be able to use the "validate" jQuery plugin with the date
option set.
There's no built-in date functionality in jQuery core...and it doesn't really do anything directly to help with dates, so there aren't many libraries on top of it (unless they're date pickers, etc). There are several JavaScript date libraries available though, to make working with them just a bit easier.
I can't answer for sure what's best...it depends how they're entering it and what culture you're dealing with, keep in mind that different cultures are used to seeing their dates in different format, as a quick example, MM/DD/YYYY
vs YYYY/MM/DD
(or dozens of others).
The best way to get user date input is a date picker that only provides valid dates. It can be done with a string, but you are liable to rile your users by demanding they use your chosen format.
You need to specify in your validator if dates precede months.
This uses a second argument to enforce the order. With no second argument it uses the computer's default order.
// computer default date format order:
Date.ddmm= (function(){
return Date.parse('2/6/2009')> Date.parse('6/2/2009');
})()
allow month names as well as digits: '21 Jan, 2000' or 'October 21,1975'
function validay(str, order){
if(order== undefined) order= Date.ddmm? 0: 1;
var day, month, D= Date.parse(str);
if(D){
str= str.split(/\W+/);
// check for a month name first:
if(/\D/.test(str[0])) day= str[1];
else if (/\D/.test(str[1])) day= str[0];
else{
day= str[order];
month= order? 0: 1;
month= parseInt(str[month], 10) || 13;
}
try{
D= new Date(D);
if(D.getDate()== parseInt(day, 10)){
if(!month || D.getMonth()== month-1) return D;
}
}
catch(er){}
}
return false;
}
The problem is that entering in February 31st will return a valid date in JavaScript. Enter in the year, month, and day, turn it into a date, and see if that date matches what you input, instead of some day in March.
function isDate(y, m, d) {
var a = new Date(y, m-1, d);
// subtract 1 from the month since .getMonth() is zero-indexed.
if (a.getFullYear() == y && a.getMonth() == m-1 && a.getDate() == d) {
return true;
} else {
return false;
}
}
Technically, this is vanilla JavaScript, since jQuery doesn't really expand on the native Date object.
Date.parse will prb sort you out, without the need for jquery:
http://www.w3schools.com/jsref/jsref_parse.asp
Above removed after some kind soul pointed out how basic parseDate really is.
There is also a $.datepicker.parseDate( format, value, options )
utility function in the JQuery UI Datepicker plugin:
https://api.jqueryui.com/datepicker/
I arrived at this solution, made more complicated as I use the European format and javascript is clearly american!
function CheckDate()
{
var D = document.getElementById('FlightDate').value;
var values = D.split("-")
var newD = values [1] + "/" + values [0] + "/" + values[2]
var d = new Date(newD);
if(d == 'Invalid Date')document.getElementById('FlightDate').value = "";
}
Messy, but does the job. If your users are american and put the day in the middle, (which I'll never understand!), then you can leave out the split and creation of the newD.
It is probable that I can override the default americanism in the JS by setting culture or some such, but my target audience is exclusively European so it was easier to rig it this way. (Oh, this worked in Chrome, haven't tested it on anything else.)
If you don't want to use the jquery plugin I found the function at:
http://www.codetoad.com/forum/17_10053.asp
Works for me. The others I found don't work so well.
UPDATED:
From the cached version of the page at: http://web.archive.org/web/20120228171226/http://www.codetoad.com/forum/17_10053.asp
// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching either
// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.
// The function returns true if a valid date, false if not.
// ******************************************************************
function isDate(dateStr) {
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
return false;
}
month = matchArray[1]; // p@rse date into variables
day = matchArray[3];
year = matchArray[5];
if (month < 1 || month > 12) { // check month range
alert("Month must be between 1 and 12.");
return false;
}
if (day < 1 || day > 31) {
alert("Day must be between 1 and 31.");
return false;
}
if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
alert("Month " + month + " doesn`t have 31 days!")
return false;
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day > 29 || (day == 29 && !isleap)) {
alert("February " + year + " doesn`t have " + day + " days!");
return false;
}
}
return true; // date is valid
}
I guess you want something like this. +1 if it works for you.
HTML
Date : <input type="text" id="txtDate" /> (mm/dd/yyyy)
<br/><br/><br/>
<input type="button" value="ValidateDate" id="btnSubmit"/>
jQuery
$(function() {
$('#btnSubmit').bind('click', function(){
var txtVal = $('#txtDate').val();
if(isDate(txtVal))
alert('Valid Date');
else
alert('Invalid Date');
});
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex
var dtArray = currVal.match(rxDatePattern); // is format OK?
if (dtArray == null)
return false;
//Checks for mm/dd/yyyy format.
dtMonth = dtArray[1];
dtDay= dtArray[3];
dtYear = dtArray[5];
if (dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay> 31)
return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
return false;
else if (dtMonth == 2)
{
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if (dtDay> 29 || (dtDay ==29 && !isleap))
return false;
}
return true;
}
});
CSS
body{
font-family:Tahoma;
font-size : 8pt;
padding-left:10px;
}
input[type="text"]
{
font-family:Tahoma;
font-size : 8pt;
width:150px;
}
DEMO
You should use moment.js it's the best lib to handle all kind of dates. Solution to your problem:
var inputVal = '2012-05-25';
moment(inputVal , 'YYYY-MM-DD', true).isValid();
精彩评论