Regex verification correct birth date and check age - asp.net

I need a regex which takes the string YYYY-MM-DD-XXXX (The last 4 are just for purpose of gender/area) It's mostly important to check the first 8 Digits for a valid birth date.
So far i have this:
/^([0-9]{4})\-([0-9]{2})\-([0-9]{2})\-([0-9]{4})$/
Also i want to check so the input age is at least 18 years old. Would appreciate if somone had some input on how to achieve this.
Edit: The regex above was tested in JS, but should work fine in ASP as well?

I have changed your regex a bit to make it look more authentic
^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$
years like 3012 will not pass.
Now you want to find whether a person is 18 years or not.
One approach could be to find the difference between the years of dates provided like this
var str = '1990-09-12-5555';
var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
var year_now = new Date().getFullYear();
console.log(year_now-res[1]);
a second approach will be more precise one :
var str = '1990-09-12-5555';
var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
var todays_date = new Date();
var birth_date = new Date(res[1],res[2],res[3]);
console.log(todays_date-birth_date);
will output the result in milliseconds. You can do the math to convert it into year
Cheers , Hope that helps !

I suggest using moment.js which provides an easy to use method for doing this.
interactive demo
function validate(date){
var eighteenYearsAgo = moment().subtract("years", 18);
var birthday = moment(date);
if (!birthday.isValid()) {
return "invalid date";
}
else if (eighteenYearsAgo.isAfter(birthday)) {
return "okay, you're good";
}
else {
return "sorry, no";
}
}
To include moment in your page, you can use CDNJS:
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>
Source

The following will match any year with a valid day/month combination, but won't do validation such as checking you've not entered 31 days for February.
^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])\-[0-9]{4}$
Not sure exactly what you're trying to achieve but I'd suggest using a date library for this sort of thing. You could return a message to the user somehow if the entered date fails to parse into an object.
In order to do age validation, you will certainly need to use a library so a regex should only be used for date validation purposes

Related

Get time format according to spreadsheet locale?

I want to store a Javascript Date() object in a spreadsheet with correct format according to spreadsheet's locale (SpreadsheetApp.getActive().getSpreadsheetLocale()).
Is there a way to get the country specific (date and) time format string from the spreadsheet locale?
E.g. when locale is de_DE, time format string as hh:mm
but when locale is da_DK, time format string as hh.mm
Interesting as well how to get the countries currency format.
BTW when I have date and time in de_DE and than change to da_DK, dates are reformatted (23.01.2020 -> 23/01/2020) but times are not (it stays as 22:59). Is that an error in Spreadsheet?
Dates in JavaScript have the method toLocaleDateString, which return a string formatted according to the specified locale. But this doesn't seem to work in Apps Script.
If you're open to using an Apps Script Web App for this, you could use this toLocaleDateString in your client-side script (that is, in a script tag in your HTML).
If that's not the case, I think your best option would be to create the relationship between formats and locales yourself, because Apps Script doesn't have a built-in method to achieve that. You could, for example, use a switch statement that would check the locale, and then format the date accordingly with Utilities.formatDate, the tool Apps Script uses to format dates. It could be something along the following lines:
var locale = SpreadsheetApp.getActive().getSpreadsheetLocale();
var formattedDate;
switch (locale) {
case 'de_DE':
formattedDate = Utilities.formatDate(yourDate, yourTimeZone, "hh:mm");
break;
case 'da_DK':
formattedDate = Utilities.formatDate(yourDate, yourTimeZone, "hh.mm");
break;
// ...
}
return formattedDate;
Reference:
toLocateDateString
Apps Script Web Apps
Utilities.formatDate
I hope this is of any help.
Sorry for that, however I found a function that would be worth checking out, it's toLocaleDateString() and toLocaleTimeString (), they deliver the local date and time format.
Please check
Formato fechas JavaScript.
I did the test from Google Apps Script and it throws me the following
function pruebafecha() {
var d = new Date();
var n = d.toLocaleDateString();
var h = d.toLocaleTimeString();
Logger.log(n);
Logger.log(h);
}
This is the answer(Colombia):
[20-01-24 16:47:50:286 EST] 24 de enero de 2020
[20-01-24 16:47:50:287 EST] 16:47:50 EST
A JavaScript Date object includes date, time and timezone. When Google Apps Script pass a Date object to the spreadsheet using setValue() / setValues() the value is displayed according to the cell number formatting using the spreadsheet timezone.
If the cell formatting is set to Automatic by default the date will be displayed accordingly to the spreadsheet locale.
If you want to force the cell to display a date in an specific format use Class Range setNumberFormat / setNumberFormats
If you don't want to use the above methods and don't want to rely on the spreadsheet locale and automatic cell format then instead of passing a Date object pass the value as an string prepending it with an ' (apostrophe, single quote character) to prevent that that automatic data type parsing changes the value and it's format.
Related
Javascript in Google Sheets script: help using setNumberFormat
I don't know very well the configuration of the sheet you mention. However, I share a code that I use to print the date and time of data submission of a form.
var d = new Date();
var hour = d.getHours()-1;
var min = d.getMinutes();
var day = d.getDate();
var month = d.getMonth()+1;
var year = d.getFullYear();
if (month<10) {dia = day+"/"+"0"+month+"/"+year;}
else {dia = day+"/"+month+"/"+year;}
if (min<10){time = hour+":"+"0"+min;}
else {time = hour+":"+min;}
What I do in the code is to take the values ​​of day, month and year, I add 1 to the value of month because it takes values ​​[0:11] => [Jan, Dec].
Then I build the format I want from date and time, you can notice that I have 1 left to the hours, because when I did the tests I noticed that the time of the script was one hour above.
I use google translate, I hope it is understood.

moment.js will not parse UK format date even when setting the locale

Quite simply, this is my code:
http://jsfiddle.net/NibblyPig/k9zb4ysp/
moment.locale('en-GB');
var d = moment('22/12/2019');
alert(d);
I would expect this to parse, however it says invalid date.
I have referenced moment.js and the locale/en-gb.js
I'm writing a global control so the date may come in in a variety of formats.
If I put in a variety of American dates they all work, for example 12/12/2019, 12/12/2019 23:04 etc.
However the locale command does not appear to do anything and I cannot get a single date to parse. What am I doing wrong?
You need to pass the format as the second argument for moment(), as discussed here:
moment.locale('en-GB');
var d = moment('22/12/2019', 'DD/MM/YYYY');
alert(d);
https://jsfiddle.net/a4gu6kfz/
From the docs:
If you know the format of an input string, you can use that to parse a
moment.
moment("12-25-1995", "MM-DD-YYYY");
I think that there is no need to write your own complex logic to parse your input, you can use moment(String, String) (or moment(String, String[], String, Boolean)), as suggested by Thales Minussi's answer.
moment(String) is the good choice only if your input is in ISO 8601 or RFC 2822 compliant form.
In your case, you can probably use Localized formats listed in the format section of the docs. If you have a list of possible formats, I think that the best choice is tho use moment(String, String[]).
Please note that, by default: Moment's parser is very forgiving, so using default Forgiving Mode will handle "any" character as separator.
Here a live sample:
moment.locale('en-GB');
['22/12/2019', '22/12/2019 15:00',
'22-12-2019', '22-12-2019 15:00',
'1-3-2019', '1-12-2019', '22-1-2019'
].forEach((elem) => {
var d = moment(elem, 'L LT');
console.log(d.format());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/en-gb.js"></script>
Still hoping there's a nice moment js way to do this but in the meantime I just bashed this together. Pretty nasty and it will probably go wrong in 80 years or so.
http://jsfiddle.net/NibblyPig/k9zb4ysp/22/
var a = "23/03/19 12:42:21.123";
var datePart = a.substring(0, a.indexOf(" "));
var timePart = a.substring(a.indexOf(" ") + 1);
var dateParts = datePart.split("/");
if (dateParts[0].length == 1) dateParts[0] = "0" + dateParts[0];
if (dateParts[1].length == 1) dateParts[1] = "0" + dateParts[1];
if (dateParts[2].length == 2) {
var threshold = parseInt(new Date().getFullYear().toString().substring(2)) + 10;
if (parseFloat(dateParts[2]) > threshold ) {
dateParts[2] = "19" + dateParts[2];
}
else
{
dateParts[2] = "20" + dateParts[2];
}
}
alert (parseFloat(dateParts[2] + dateParts[1] + dateParts[0] + timePart.replace(/:/g, "").replace(/\./g, "")));
This won't solve every usecase, but in your specific example if you want just a simple date (with no time component) auto-parsed in UK format you can just use the 'L' format string having set the locale to 'en-GB'
Your example with this change (your jsfiddle also)
moment.locale('en-GB');
// just pass 'L' i.e. local date format as a parsing format here
var d = moment('22/12/2019', 'L');
alert(d);
It's quite nice because you get the auto parsing of various formats you wanted for free. For instance this works just the same:
var d = moment('22-12-2019', 'L');
You can return a date using moment.js in a desired format -
return moment(aDateVar).format('DD/MM/YYYY');

Parse alfresco date

I'm developing a custom validator of a date input in my workflow form and I get a null after parsing a date this is what I done:
// check dates can be parsed
str_expiryDate = field.form.prop_wfbxTestWorkFlow_NfDate.value;
console.log("Non conformite"+str_expiryDate);
str_reminderDate = field.form.prop_bpm_workflowDueDate.value;
console.log("echeance"+str_reminderDate);
Alfresco.logger.warn("Expiry Date: " + str_expiryDate + " | Reminder Date: " + str_reminderDate);
d_expiryDate = Date.parse(str_expiryDate);
console.log("nfDate"+str_expiryDate);
d_reminderDate = Date.parse(str_reminderDate);
console.log("Date echéance"+d_reminderDate);
and then i get this in console:
Non conformite2013-06-21T00:00:00.000+01:00 echeance2013-06-09T00:00:00.000+01:00
nfDatenull
Date echéancenull
How I can parse these two dates and then compare it? .thanks
Use Alfresco.util.fromISO8601(date)
According to the client-api docs
Convert an ISO8601 date string into a JavaScript native Date object
You are parsing the "value" of a date, not the date itself.
The best way to compare is, imho, using the format YYYYMMDD, and than compare it as a number.
Something like this (there is sure a far more elegant way to do that, but at this time it's the only one that got me):
var indexDate=str_expiryDate.indexOf("-");
var dayDate=str_expiryDate.substring(0, 2);
var monthDate=str_expiryDate.substring(3, 5);
var yearDate=fromData.substring(6, str_expiryDate.length+1);
int dataNew=yearDate+monthDate+dayDate;
and than compare the two dates value.
Obviously check if the index value are correct, I didn't double checked them.
Hope il helps.

Reformatting date in google spreadsheet

I'm setting up a spreadsheet for someone else with a form to enter data.
One of the columns is supposed to hold a date. The input date format is like this example: "Jan 26, 2013" (there will be a lot of copy & paste involved to collect data, so changing the format at input step is not a real option).
I need this date column to be sortable, but the spreadsheet doesn't recognize this as a date but simply as a string. (It would recognize "Jan-26-2013", I've tried.)
So I need to reformat the input date.
My question is: how can I do this? I have looked around and google apps script looks like the way to go (though I haven't found a good example of reformatting yet).
Unfortunately my only programming experience is in Python, and of intermediate level. I could do this in Python without a problem, but I don't know any JavaScript.
(My Python approach would be:
splitted = date.split()
newdate = "-".join([splitted[0], splitted[1][:-1], splitted[2]])
return newdate
)
I also don't know how I'd go about linking the script to the spreadsheet - would I attach it to the cell, or the form, or where? And how? Any link to a helpful, understandable tutorial etc. on this point would help greatly.
Any help greatly appreciated!
Edit: Here's the code I ended up with:
//Function to filter unwanted " chars from date entries
function reformatDate() {
var sheet = SpreadsheetApp.getActiveSheet();
var startrow = 2;
var firstcolumn = 6;
var columnspan = 1;
var lastrow = sheet.getLastRow();
var dates = sheet.getRange(startrow, firstcolumn, lastrow, columnspan).getValues();
newdates = []
for(var i in dates){
var mydate = dates[i][0];
try
{
var newdate = mydate.replace(/"/g,'');
}
catch(err)
{
var newdate = mydate
}
newdates.push([newdate]);
}
sheet.getRange(startrow, firstcolumn, lastrow, columnspan).setValues(newdates)
}
For other confused google-script Newbies like me:
attaching the script to the spreadsheet works by creating the script from within the spreadsheet (Tools => Script Editor). Just putting the function in there is enough, you don't seem to need a function call etc.
you select the trigger of the script from the Script Editor (Resources => This Project's Triggers).
Important: the script will only work if there's an empty row at the bottom of the sheet in question!
Just an idea :
If you double click on your date string in the spreadsheet you will see that its real value that makes it a string instead of a date object is this 'Jan 26, 2013 with the ' in front of the string that I didn't add here...(The form does that to allow you to type what you want in the text area, including +322475... for example if it is a phone number, that's a known trick in spreadsheets cells) You could simply make a script that runs on form submit and that removes the ' in the cells, I guess the spreadsheet would do the rest... (I didn't test that so give it a try and consider this as a suggestion).
To remove the ' you can simply use the .replace() method **
var newValue = value.replace(/'/g,'');
here are some links to the relevant documentation : link1 link2
EDIT following your comment :
It could be simpler since the replace doesn't generate an error if no match is found. So you could make it like this :
function reformatDate() {
var sheet = SpreadsheetApp.getActiveSheet();
var dates = sheet.getRange(2, 6, sheet.getLastRow(), 1).getValues();
newdates = []
for(var i in dates){
var mydate = dates[i][0];
var newdate = mydate.replace(/"/g,'');
newdates.push([newdate]);
}
sheet.getRange(2, 6, sheet.getLastRow(), 1).setValues(newdates)
}
Also, you used the " in your code, presumably on purpose... my test showed ' instead. What made you make this choice ?
Solved it, I just had to change the comma to dot and it worked

Javascript Date Localization

I'm working with an ASP.NET app with localization and globalization. I'm having some difficulty understanding how to get the Date() function in javascript to work properly given the user's environment. My user base is split between Mexico (spanish) and the US (english). Since the Mexico date format is dd/mm/yyyy and the english format is mm/dd/yyyy, the standard Date(strDate) javascript constructor does not work for me.
Does anyone know the best way to handle globalization/localization of a javascript Date value? I have some business rules to enforce like dateA must be 90 days prior to dateB and dateB cannot exceed today.
Take a look at datejs, it handles localization very nicely. It comes with a lot of globalization setups. You just load the globalization setup of your current CultureInfo and datejs takes care of the rest.
Matt Kruse developed a really interesting date library which should help with your particular case.
Here's a snippet of the method you should use for the issue you mentioned:
// ------------------------------------------------------------------
// parseDate( date_string [, prefer_euro_format] )
//
// This function takes a date string and tries to match it to a
// number of possible date formats to get the value. It will try to
// match against the following international formats, in this order:
// y-M-d MMM d, y MMM d,y y-MMM-d d-MMM-y MMM d
// M/d/y M-d-y M.d.y MMM-d M/d M-d
// d/M/y d-M-y d.M.y d-MMM d/M d-M
// A second argument may be passed to instruct the method to search
// for formats like d/M/y (european format) before M/d/y (American).
// Returns a Date object or null if no patterns match.
// ------------------------------------------------------------------
function parseDate(val) {
var preferEuro=(arguments.length==2)?arguments[1]:false;
generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');
monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');
dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');
var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');
var d=null;
for (var i=0; i<checkList.length; i++) {
var l=window[checkList[i]];
for (var j=0; j<l.length; j++) {
d=getDateFromFormat(val,l[j]);
if (d!=0) { return new Date(d); }
}
}
return null;
}
You could use: var a = Date.parseLocale(value, formats);
If you provide no custom formats, this function uses the Sys.CultureInfo.CurrentCulture property to determine the culture value.
You can take a look on: http://msdn.microsoft.com/en-us/library/bb397521.aspx
I wrote an answer to this here. It uses the toLocalString to determine MM/DD/YYY, DD/MM/YYYY,...
https://stackoverflow.com/a/18154195/119741

Resources