I found a very useful regular expression for testing format and content of a date field in a regex example site
BUT I get a validation when I put in dates older than 2000 and since this is a field for inputting date of birth you can see why it would be a problem. I am sure it is an easy fix but regular expressions intimidate me.
$('#txtDOB').blur(function() {
//$('span.error-keyup-5').remove();
var inputVal = $(this).val();
var dateReg = /^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/;
if(!dateReg.test(inputVal)) {
alert('invalid date format: ' + inputVal);
}
I am not married to this solution so if you can suggest a better way please comment away.
Instead of testing if a string matches one or more formats that you think might be good dates, I would suggest instead asking JavaScript if it thinks it is a valid date:
function isValidDate(str){
return !isNaN(new Date(str));
}
This assumes that you're going to accept what the user gives you in any of a variety of formats (e.g. the horrid US MM/DD/YYYY or the more sane ISO8601 YYYY-MM-DD). If instead you have a specific format you will only accept, then parse your string based on that, pull out the year/month/date, and then ask JavaScript if this is a valid date:
function isValidDate(year, month, date) {
var d = new Date(year*=1, month-=1, date*=1, 12); // noon to skip DST issues
return d.getFullYear()==year && d.getMonth()==month; // wrong date->wrong month
}
You need to check that the year/month/date all match because new Date(2011,11,32) is accepted and interpreted as 2012-1-1.
See also: Javascript method to ensure that a date is valid
There's a whole lot of mess there. First, eliminate all the {1}'s. That just means one instance, which is totally redundant. Also, a character class with one value is the same as the character itself. So, [1] becomes 1.
So, that leaves us with:
/^[01]?\d\/(([0-2]?\d)|([3][01]))\/((199\d)|([2-9]\d{3}))$/
This is MM/DD/YYYY presumably. but the YYYY is just 199[0-9] and any year > 2000 and < 9999. Wow, that's a date range!
As a basic, try:
/^[01]?\d\/(([0-2]?\d)|([3][01]))\/([12]\d{3}))$/
This gives a year range of 1000 - 2999. But as Tim said above, if you want really valid dates, you should use a specific date validator.
If you need to parse date strings into dates then I would check out this library:
DateJS
Related
I'd like to check whether a string does represent a Date with an given format.
I tried Date.parse(string, format) but it parses the string to date even if it's in a whole different format. E.g.:
Date.parse("2015-07-04T23:10:00.000+02:00", "yyyy-MM-ddTHH:mm:ss.SSSZ") // Parsed as a date
Date.parse("2000", "yyyy-MM-ddTHH:mm:ss.SSSZ") // Parsed as a date also`
I don't want to parse the second row as a date, because its not in the required format.
I also tried Date.parseExact() method of Date.js but it didn't parsed the date if I provided a timezone and a format like above.
The right solution was based on RobG's comment: (but thanks to everyone for helping me)
moment("2015-07-04T23:10:00.000+02:00", "yyyy-MM-ddTHH:mm:ss.SSSZ", true).isValid()
Every other solution succeeded the parsing even if the input was only a year which I tried to avoid. The last parameter "true" stands for the "strict" parsing which provides exactly the output that I was looking for.
You can leverage MomentJS and its function .format()
How does it work? here is the documentation, it's fairly simple, you wanna use your string in combination with the format string.
MomentJS .format()
And here is the quick demo Fiddle:
var myString = "2015-07-04T23:10:00.000+02:00";
var formatString = "yyyy-MM-ddTHH:mm:ss.SSSZ";
if (moment(myString, formatString)._i == myString) console.log("GOOD");
1-liner with momentJS
I basically format your string in targeted format then check if the result matches your string.
Worth noting is that MomentJS is (IMHO) the best date and time lib for JS. I never found a reason to venture beyond it since I discovered it, after using some of the less capable libs in the past.
If you don't wanna use lib, making a regex to suit your needs is a viable alternative of similar length.
Altho, if you intend to work with a lot of dates/times, MomentJS is still a way to go as it offers so many useful things which cannot be done by regexes alone.
Why not use regular expression to check if input matches the format and parse it if it does?
reg=new RegExp(/[0-9]{4}\-[0-9]{2}\-[0-9]{2}T[0-9]{2}\:[0-9]{2}\:[0-9]{2}\.[0-9]{3}\+[0-9]{2}\:[0-9]{2}/);
str="2015-07-04T23:10:00.000+02:00";
date=new Date(str);
if(str.match(reg) && date.toString()!='Invalid Date')
{
Date.parse(str);
}
Edited to add date check.
I'm using moment-with-locales.min.js for date manipulation and I need to format as the user leaves the textboxes. Because locales are an issue, I'm trying to use moment to do the formatting. However, I'm running into a problem and I'm not sure if I'm doing it wrong or what.
If the user types in something like '2/2/12' and I try to do moment('2/2/12', 'l'), using the 'l' for short date based on locale, it formats it into '2/2/0012'. That in itself seems broken.
If I try to format with moment('2/2/12', 'M/d/yyyy'), as seen in the JSFiddle below, it changes it to '2/1/2014'. It always bumps it down to the first day of the month and makes it the current year.
Here's the JSFiddle I was using.
moment.locale('en-US');
var parsed = moment('2/2/12', 'M/d/yyyy');
if (moment(parsed).isValid()) {
var d = new moment(parsed, 'l');
alert('Pass: ' + d.format('l'));
} else {
alert('Fail: ' + parsed);
}
I'd appreciate and help.
You should use "D" ("d" is day of week).
As for the year, according to the docs, «Two digit year parser by default assumes years above 68 to be in the 1900's and below in the 2000's.» so I'm guessing (and experimentation seems to confirm it) that if you use the 4 digit format ("YYYY") it'll assume you are passing in the year 12 and not 2012. If you use "YY" it'll print 2012 correctly.
So, to summarize, the format "M/D/YY" should do what you want.
I just learned regular expressions and I created a dd-mm-yyyy date validator with regular expressions:
^(0[1-9]|[12][0-9]|3[01])([-/.])(0[1-9]|1[0-2])\2(19|20)\d\d$
Debuggex Demo
It seems to work fine. But i was wondering if there are any improvements that could be made to make sure there will be no errors. Any suggestions?
Why reinvent the wheel. Take help of built-in date parsing method Date.parse(String) like this:
var timestamp = Date.parse(str); // str is your input string for data
var date = null
if (isNaN(timestamp) == false)
date = new Date(timestamp);
else
alert("Invalid date");
Maybe you want to include moment.js into your project? Then you can just write:
moment("not a real date").isValid(); // false
You can also use your own format string if you want to. ;-) This would also give you the advantage that it veryfies if the date actually exists (think of 29-02-2013, which is not existant).
I have a date of birth like 12-08-1989 in text box in HTML.I want to validate that the user must be of 18 years old in javascript.
I have used Date function in javascript but it seems like it accept YYYY-MM-DD format but i want to validate in DD-MM-YYYY.
How can I achieve this?
var pattern =/^([0-9]{2})-([0-9]{2})-([0-9]{4})$/;
if(pattern.test(str_input_date))
{
alert("valid date");
}
This should give you a start. :)
You should probably be using some validation framework, like jQuery.validation. This is by far more consistent way to handle validation in your code. If this is the only validated field in your app, you can, of course, use naive implementation as provided above.
Whether you need some advanced date validation rules, you could use a JS date framework, like Moment.js (or Date.js, which is pretty outdated at the moment).
you can use the date class, just like this
try{
var x=new Date('1/1/2001');
var Cnow=new Date();//current Date
if(Cnow.getFullYear()- x.getFullYear()<18){
alert('not old enough');
}
else{
//success !!!
}
}
catch(ejs){alert('invalid')}
"I have used Date function in javascript but it seems like it accept YYYY-MM-DD format but i want to validate in DD-MM-YYYY"
You can create a Date object by passing the year, month and day (and, optionally, the hour, minute, second, and millisecond) values separately:
var aDate = new Date(2012, 5, 22);
So if you use a regex or other string methods to extract the pieces from what the user entered then you can create a date from DD-MM-YYYY (or whatever other) format you like.
The way I'd test if the user is at least 18 years old would be to add 18 years to their date of birth and see if that is on or before today's date:
aDate.setFullYear( aDate.getFullYear() + 18 )
The various methods available on a Date object are listed at MDN.
I need a way to turn my 2 character string dates (i.e. '04/10/2010' & '05/24/2010') into an integers to see if one is greater than the other. If the user enters an end date that is less than the begin date I need to popup an "invalid date range" error.
From what you posted your real problem is:
I need to see if one date is greater than another in javascript/jquery.
If so all you need to use is the Javascript Date object (how to page here).
You can use it as follows:
var dateTextA = '04/10/2010';
var dateTextB = '05/24/2010';
var dateA = new Date(dateTextA);
var dateB = new Date(dateTextB);
if (dateA < dateB){
alert("Your date is out of range!");
}
Note: Above code has been tested and works in IE7.
If you really feel you need an integer value, you can use the UTC function to get that.
The problem is Date.parse('04/10/2010') returns a timestamp (integer) for April 10 in the US and 4 October most other places.
It is best to use a less ambiguous format - if you are taking user input, give the user a calendar, menu, or three label inputs, then build the date from that.
3 inputs:
new Date(+fullyearinput, monthinput-1, +dateinput)
If Date won't parse what you are looking for, Datejs provides a lot of syntactic sugar to make your life easier.
To compare two dates, all you need to do is turn your strings into Date objects and then use the greater than, less than, or equality operators. Javascript provides Date comparison natively.