How to check date validation in regex using js? [duplicate] - javascript

This question already has answers here:
Javascript: how to validate dates in format MM-DD-YYYY?
(21 answers)
Closed 6 years ago.
I am trying to validate date in js ("yyyy/mm/dd") format. After googling I found other date format checked but I can't get in this format.
Any one plz can help me out.
Here is my code.
function dateChecker()
{
var date1, string, re;
re = new RegExp("\d{4}/\d{1,2}/\{1,2}");
date1 = document.getElementById("visitDate").value;
if(date1.length == 0)
{
document.getElementById("showError").innerHTML = "Plz Insert Date";
document.getElementById("showError").style.color = "red";
}
else if(date1.match(re))
{
document.getElementById("showError").innerHTML = "Ok";
document.getElementById("showError").style.color = "red";
}
else
{
document.getElementById("showError").innerHTML = "It is not a date";
document.getElementById("showError").style.color = "red";
}
}

Try this:
var date = "2017/01/13";
var regex = /^[0-9]{4}[\/][0-9]{2}[\/][0-9]{2}$/g;
console.log(regex.test(date)); // true
console.log(regex.test("13/01/2017")); //false
console.log(regex.test("2017-01-13")); // false

If you use new RegExp then you must call compile on the resulting regular expression object.
re = new RegExp("\d{4}/\d{1,2}/\d{1,2}");
re.compile();
Alternatively you could write the regex this way which does not require compile to be called.
re = /\d{4}\/\d{1,2}\/\d{1,2}/;
EDIT
Note that the above regex is not correct (ie it can approve invalid dates). I guess the brief answer is, don't use regex to validate date times. Use some datetime library like momentjs or datejs. There is too much logic. For instance, how do you handle leap years, different months having different number of possible days, etc. Its just a pain. Use a library that can parse it, if it cant be parsed, its not a date time. Trust the library.
However you could get closer with something like this
re = /^\d{4}\/(10|11|12|\d)\/((1|2)?\d|30|31)$/;
Also if you want to get comfortable with regex, download Expresso

Related

Return the date format for date without moment.js

I can't figure out how to build a function that does this
INPUT: dateToDateFormat('16/07/2022') -> OUTPUT: DD/MM/YYYY
INPUT: dateToDateFormat('07/16/2022') -> OUTPUT: MM/DD/YYYY
The input dates will be already formatted by .toLocaleString function
Edit:
I think I was not precise enough with the output, it should literally output MM/DD/YYYY as a string, not the actual date value
A) First of all, your desired date string conversion seems to be easy (solution below) without using any package/overhead.
B) However, if you need to process it further as a JS Date Object, things become more difficult. In this case, I like to provide some useful code snippets at least which might help you depending on your usecase is or what you are aiming for.
A) CONVERSION
Seems you need a simple swap of day and month in your date string?
In this case, you do not need to install and import the overhead of a package such as date-fns, moment or day.js.
You can use the following function:
const date1 = "16/07/2022"
const date2 = "07/16/2022"
const dateToDateFormat = (date) => {
const obj = date.split(/\//);
return `${obj[1]}/${obj[0]}/${obj[2]}`;
};
console.log("New date1:", dateToDateFormat(date1))
console.log("New date2:", dateToDateFormat(date2))
B) STRING TO DATE
Are you using your date results to simply render it as string in the frontend? In this case, the following part might be less relevant.
However, in case of processing them by using a JS Date Object, you should be aware of the following. Unfortunately, you will not be able to convert all of your desired date results/formats, here in this case date strings "16/07/2022" & "07/16/2022", with native or common JS methods to JS Date Objects in an easy way due to my understanding. Check and run the following code snippet to see what I mean:
const newDate1 = '07/16/2022'
const newDate2 = '16/07/2022'
const dateFormat1 = new Date(newDate1);
const dateFormat2 = new Date(newDate2);
console.log("dateFormat1", dateFormat1);
console.log("dateFormat2", dateFormat2);
dateFormat2 with its leading 16 results in an 'invalid date'. You can receive more details about this topic in Mozilla's documentation. Furthermore, dateFormat1 can be converted to a valid date format but the result is not correct as the day is the 15th and not 16th. This is because JS works with arrays in this case and they are zero-based. This means that JavaScript starts counting from zero when it indexes an array (... without going into further details).
CHECK VALIDITY
In general, if you need to further process a date string, here "16/07/2022" or "07/16/2022", by converting it to a JS Date Object, you can in any case check if you succeed and a simple conversion with JS methods provides a valid Date format with the following function. At least you have kind of a control over the 'invalid date' problem:
const newDate1 = '07/16/2022'
const newDate2 = '16/07/2022'
const dateFormat1 = new Date(newDate1);
const dateFormat2 = new Date(newDate2);
function isDateValidFormat(date) {
return date instanceof Date && !isNaN(date);
}
console.log("JS Date Object?", isDateValidFormat(dateFormat1));
console.log("JS Date Object?", isDateValidFormat(dateFormat2));
Now, what is the benefit? You can use this function for further processing of your date format depending on what you need it for. As I said, it will not help us too much as we still can have valid date formats but with a falsy output (15th instead of 16th).
CONVERT TO DATE OBJECT BY KNOWING THE FORMAT
The following function converts any of your provided kinds of dates ("MM/DD/YYYY" or "DD/MM/YYYY") to a valid JS Date Object and - at the same time - a correct date. However, drawback is that it assumes to know what kind of input is used; "MM/DD/YYYY" or "DD/MM/YYYY". The dilemma is, that this information is crucial. For example, JS does not know if, for example, "07/12/2022" is "MM/DD/YYYY" or "DD/MM/YYYY". It would return a wrong result.
const newDate1 = "07/16/2022"
const newDate2 = "16/07/2022"
function convertToValidDateObject(date, inputFormat) {
const obj = date.split(/\//);
const obj0 = Number(obj[0])
const obj1 = Number(obj[1])
const obj2 = obj[2]
//
// CHECK INPUT FORMAT
if (inputFormat === "MM/DD/YYYY") {
return new Date(obj2, obj0-1, obj1+1);
} else if (inputFormat === "DD/MM/YYYY") {
return new Date(obj2, obj1-1, obj0+1);
} else {
return "ERROR! Check, if your input is valid!"
}
}
console.log("newDate1:", convertToValidDateObject(newDate1, "MM/DD/YYYY"))
console.log("newDate2:", convertToValidDateObject(newDate2, "DD/MM/YYYY"))
console.log("newDate2:", convertToValidDateObject(newDate2, "MM/YYYY"))
If the wrong format is provided as a second argument, an error is provided in the console. In practise I suggest you to use a try-catch block ( I tried here, but it does not work here in this stackoverflow editor).
I wish you good luck. Hope these information can help you.

Javascript / Elastic COMPLEX Date Math Regex

I am trying to validate a user input date range. We can accept ISO8601 formatted dates and Date Math Expressions since I am passing it into elasticsearch.
Due to the way the code is, they enter it via an input box so I have to validate the text manually and force them into correct input (unable to transform to proper format).
Sample valid user inputs:
[2021 to 2022]
[2020-12-25T14:48Z to now]
[now-5y to now+1w]
[2020-12-25+1M to now-1m]
Sample invalid user inputs:
[2020-12-25tt4:48Z to now]
[NOW-5y to now+1w]
[now-5y too now+1w]
[2020-12-25+1M To now-1h/d]
So far I [think] I have found a way to confirm the valid ISO8601 and range delimiter but I am having trouble with the regex for the + - / options. This is a snippet of my code so far:
const ALLOWED_NOW_CONSTANTS = /\bnow([+-/][1-9][yMwdhHms])?/; // ISSUE WITH DATE MATHS HERE
const ISO_8601 = /^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/; // ISSUE ADDING DATE MATHS TO THIS ALSO
const validateDateExpression = (dateStr) => {
return ALLOWED_NOW_CONSTANTS.test(dateStr) || ISO_8601.test(dateStr);
}
const str = userInput.trim();
if (str.startsWith('[') && str.endsWith(']')) {
const dateExpression = trim(str, '[]').split(/(\bto\b)/i);
if (dateExpression.length !== 3) {
return '[startTime to endTime]'
}
if ( !validateDateExpression(dateExpression[0].trim()) ) {
return `${dateExpression[0]} is not a valid format`;
}
if ( !validateDateExpression(dateExpression[2].trim()) ) {
return `${dateExpression[2]} is not a valid format`;
}
return ''
}
So my issue with my regex is for the optional "rounded" date maths as well as the date maths for ISO8601. I want to be able to put in the valid date maths but the : now, now/d, now-3M/y, now-1h/d, 2017-03-22+1y, 2020-12-25T14:48:10.78Z+5w/M, 2020-12-25T14:48:10.78Z/M, etc. are cases where I can't seem to get a regex working for this.
This is because of the optional cases where if it is / then it has to be the yMwdhHms that follows instead of a digit. I can't figure out a regex to get this working (now+8h/d or now/y) .
This is also an issue for my ISO8601 date since they can add the date maths at the end and the ISO8601 date is so flexible.
Any help with this is appreciated.
If anything needs clarification on my end or if there's better solutions to this within my current restrictions let me know.

Find dates in text [duplicate]

This question already has answers here:
Javascript date regex DD/MM/YYYY
(13 answers)
Closed 7 years ago.
I want to find Dates in a document.
And return this Dates in an array.
Lets suppose I have this text:
On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994
Now my code should return ['03/09/2015','27-03-1994'] or simply two Date objects in an array.
My idea was to solve this problem with regex, but the method search() only returns one result and with test() I only can test a string!
How would you try to solve it? Espacially when you dont know the exact format of the Date? Thanks
You can use match() with regex /\d{2}([\/.-])\d{2}\1\d{4}/g
var str = 'On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994';
var res = str.match(/\d{2}([\/.-])\d{2}\1\d{4}/g);
document.getElementById('out').value = res;
<input id="out">
Or you can do something like this with help of capturing group
var str = 'On the 03/09/2015 I am swiming in a pool, that was build on the 27-03-1994';
var res = str.match(/\d{2}(\D)\d{2}\1\d{4}/g);
document.getElementById('out').value = res;
<input id="out">

Get time difference between two date strings

I want to develop a JavaScript function to calculate the activity of users based on the date in the server where the data is stored. The problem is that the date is a string like this:
2013-08-11T20:17:08.468Z
How can I compare two string like this to calculate minor and major time as in the example?
If you want to compare two dates just use this :
var dateA = '2013-08-11T20:17:08.468Z';
var parsedDateA = new Date(dateA).getTime();
var dateB = '2013-06-06T17:33:08.468Z';
var parsedDateB = new Date(dateB).getTime();
if(parsedDateA > parsedDateB) {
// do something
}
Assuming you need to do the comparisons client-side, the best way is to load the dates into Date objects using Date.parse. Then compare them using the functions provided for Date, such as getTime.
Try parse method:
var s = "2013-08-11T20:17:08.468Z";
var d = Date.parse(s);
As I have understood you in the right way, there is a good answer to your question here.
You can also look at this very good Library (DateJS).
If your problem was converting from the Date-String to js-Date look at this Page.

Breaking down a date into segments [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Simplest way to parse a Date in Javascript
I understand how do get the data and break it down into it's segments, i.e.
alert( ( new Date ).getDate() );
and
alert( ( new Date ).getFullYear() );
alert( ( new Date ).getFullMonth() );
etc etc.
But how do I do the same but use a date from a html textbox? instead of reading new Date?
The date in the HTML box would be formated as follows
31/10/2012
You could try:
var datearray = input.value.split("/");
var date = new Date(datearray[2],datearray[1] - 1,datearray[0])
If your textbox has proper string format for a date object you can use:
var aDate = new Date($("textbox").val());
However, if you dont write it in the text box exactly as you would in a string passing to the object, you'll get null for your variable.
FYI, I made a plugin that "extends" the Date object pretty nicely and has preformatted date/times that include things like a basic SQL datetime format.
Just go to this jsFiddle, Copy the code between Begin Plugin and End Plugin into a js file and link it in your header after your jQuery.
The use is as simple as above example:
var aDate = new DateTime($("textbox").val());
And to get a specific format from that you do:
var sqlDate = aDate.formats.compound.mySQL;

Categories