Date Of Birth Validation in JavaScript? - javascript

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.

Related

Managing multiple date formats in Javascript

Similar questions has been asked many times but I couldn't find a more concrete solution. The things I'm doing are:
I have a <input type="date"> inside my HTML which when clicked opens a calender with date in dd/mm/yyyy format.
I change the html5 date to timestamp to send to my db by Date.parse(html5Date) and in the server I modify the date and send it back to my Angular app.
I now convert the timestamp back to Date object by new Date(timestamp).To print the date in a human-friendly format inside a table I do [date.getDate(), date.getMonth() + 1, date.getFullYear()].join('/').
On edit (PUT request), I again capture the date from HTML, convert it to timestamp, send it to server and process the returning date back to html date.
Other than these, I also do a ton of functionalities like date comparison, adding hours to the dates, show time of the day etc inside the HTML:
Just these simple operations are over 120 lines of code which I think is ridiculous and error prone. I've looked into Angular Datepicker but it's a bit confusing. Also sometimes the HTML date is of type Object and sometimes it's String so Date.parse() gives error.
Are there any developer friendly methods that does : copy HTML5 date (from datepicker) --> change to timestamp (for angular&server) --> format timestamp back to string/object (for html)? Thank You :)
Note: Angular throws a lot of annoying error in console saying dateformat is wrong (being html date type) but doesn't stop code from running
Sounds like you are doing waaay to many conversions. I would argue that there should only be one way dates are represented: as Date objects in the programming language. There are only a few conversions that need to happen:
Date <=> Integer milliseconds since the epoch to pass to server
Date <=> String human-readable format to display to user
Any thing beyond this is asking for trouble. Comparisons can be made by casting to int date.getTime(), comparing, and casting back to Date. Ditto for additions. Note that Date.parse is implementation dependent in what it will accept, although all of them will accept ISO 8601 formatted date strings anything else is guesswork. Which means you will have to deal with converting strings by hand, something like the following:
var toDate = str => {
var splitter = str.indexOf("/") === -1 ? "-" : "/";
var [mon, day, year] = str.split(splitter);
return new Date(year, mon - 1, day);
};
var toDateString = date => {
return "" + date.getFullYear() + (date.getMonth() + 1) +...
};
Note that there's no validation, that's left as an exercise to the reader.
A WORD ABOUT MOMENT.JS
moment.js is awesome. Its also huge, its a kitchen-sink API with a heft to match. You're already loading angular, so think carefully before bulking the size of your payload with another huge library.
Moment.js is a powerful date formatting and manipulation library. A lot of things you can do in Moment.js are a single line of code, which makes life a lot easier. I agree, without using a library like this date formatting and handling can be a pain.
http://momentjs.com/
EDIT: fyi, I use this with my Angular app and find it extremely useful!

How do I get this JavaScript / moment code to work with both US and UK date formats?

How do I get this JavaScript / moment code to work with both US (MM/DD/YYYY) and UK (DD/MM/YYYY) date formats? Currently it only works with a UK format:
moment.fn.toJSON = function() {
return this.format("YYYY-MM-DDTHH:mmZ");
};
function submitform() {
document.getElementById("st_dt_tm").value =
moment(document.getElementById("inp-st").value, "DD/MM/YYYY HH:mm").toJSON();
return true;
};
There is no way, by date format alone, to know if it is DD/MM/YYYY or MM/DD/YYYY because of dates like 01/02/2016, which is a valid (but different) date either way.
Your choices are:
Use MM/DD/YYYY for US dates and DD-MM-YYYY for European dates, which is similar to what the JavaScript Date object does, but even that is not entirely useful -- more details here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
The "best" option is to use some kind of cultural indicator flag -- either something passed in from the back-end code, or perhaps asking JavaScript to format a date for you and looking at what format they use -- and changing strings accordingly.

How to add three days to a given date in JavaScript?

I have one text box. When I enter a date with the format MM/DD/YYYY in that textbox and click outside the textbox I need to display the result as MM/DD/YYYY+3 using JavaScript.
For example, if my date is 12/31/2013 then the result would be 01/03/2014.
Hope this link will help you to find the answer:
adding-number-of-days-to-an-entered-date-in-javascript.
Have a look at the excellent library moment.js with which you easily can add three days to your original date.
In your case it would be something like:
var input = moment(myTextBoxValue);
input.add('d', 3); // input is now 3 days later
I guess the easiest to program and best readable solution would be to use a dedicated library for handling dates, such as Moment.js.
There, you have got the add function which allows you to add an arbitrary amount of time to a given point in time. E.g.:
moment().add('days', 7);
If you use the moment function to parse the time entered, use that as your source value, call add on it, and return it as JavaScript Date using the toDate function, you get exactly what you want.
So basically it comes down to:
var sourceDate = moment(new Date(2013, 7, 8)),
targetDate = sourceDate.add('days', 3),
result = targetDate.toDate();
Then, result contains the Date object you wanted to have.
I'd prefer that over native JavaScript handling of Date, as it is way more readble and hence understandable.

Regex for testing date formatting

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

Manipulating dates in Javascript without the Date object

It appears I can't use the javascript Date object as it inherintly defaults to US dates when you initialise with a datestring. There is no way of passing any culture information to the date object
I.e. No matter what the clients locale settings are
var d = new Date("08/10/2009") will always create a date object representing the 10th August 2009 rather than the 8th October 2009 if the clients locale was the UK.
So given that my requirement is to be able to add/subtract days/months/years easily is there a clever way of doing this easily without the Date object
All i need to do is add a day to a date (or a string representation of a date). so if my code detects the locale setttings are in the US, when it sees a string like "10/08/2009" it whacks it up to "10/09/2009" but if it had detected it was in the UK it would have know it a uk string representation of a date and whacked it up to "09/10/2009"
For date manipulation and localization on JavaScript I always recommend the DateJS library.
This library abstracts the use of Date objects, has a very good localization options, powerful date parsing and formatting, and it also has a very nice fluent API.
If you know you are getting input formatted dd/mm/yyyy you can easily assemble the correct date.
function britDay(D){
D= D.match(/\d+/g);
return new Date(+D[2], D[1]-1, +D[0]);
}
toLocaleDateString will return the date in the format expected by the user.
Relying on the user input that obeys particular formatting rules is optimistic-
which is why most sites use separate, labeled inputs or select fields for the month, date and year.
You probably know that it's easy to add one day to a date, just add 86,400 * 1000 milliseconds to the date. It sounds like displaying in your locale is the issue; does Date.toLocaleString() not do the right thing for you?
dojo.date.locale.parse will be able to parse a formatted string according the locale of your choice. It has a table of cultural data based off unicode.org/cldr. See this article for more information.

Categories