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).
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.
There is a dynamic date format where user can specify it somewhere. I need to validate the user input (most likely via js) on a date field when he input it manually (not via datepicker).
I tried moment.js but string date like '30-01-20167' is still valid even if the date format is 'dd-MM-yyyy'
I mean is there really a reliable way to do this?
var dateFormat = "DD-MM-YYYY";
moment('30-01-20167',dateFormat, true).isValid(); // false;
moment('30-01-2016',dateFormat, true).isValid(); // true;
PS: It's better to show your code directly.
You can use javascript Date to evaluate your string:
function isValidDate(dateStr) {
return !isNaN(new Date(dateStr));
}
console.log(
isValidDate('30-01-20167'),
isValidDate('12-30-2016')
)
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 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
I am currently having some issues converting a string dateTime object in JavaScript
I am assuming it is because my string cannot me used properly in a new Date() but I'm not sure that is the problem.
My Input: "2011-09-29 14:58:12"
My code:
var date = "2011-09-29 14:58:12";
var added = new Date(date);
var year = added.getYear();
However, my year var contains NaN. Same with getDay() or getMonth(). What is the problem?
ps: I'm getting the date in it's format from a SQLite database. And I'm using Titanium Mobile, so javascript and SQLite are the only things involved
You're relying on the Date constructor parsing an unsupported format. Until recently, there was no standard string format supported by the Date constructor. As of ECMAScript5, there is one (YYYY-MM-DDTHH:MM:SS, note the T rather than space), but it's only been specified for just under two years and naturally doesn't work in older browsers.
For the time being, your best bet is to parse it yourself (you can find code in this question and its answers), or use something like DateJS, MomentJS, date-fns, etc. to parse it for you.
The Date constructor will not parse a string for you. You'll need to use Date.parse to do that. Interestingly enough, Date.parse doesn't actually return a Date. Instead it returns a unix timestamp. You can then pass the unix timestamp into the Date constructor to get what you're looking for.
var d = new Date(Date.parse("2011-09-29 14:58:12"));