Regex date expression not working - javascript

I have a javascript function that does some date validation.
var regex = new RegExp(my regex expression is here);
var result = regex.test(valueToTest);
However, I've been chasing my tail for the last couple of hours because the test always returned false.
This does not work
^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\d\d$
This does not work
^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\d{2}$
This works
^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)[0-9]{2}$
The only difference between the 3 patterns is the final 2 digits. All look perfectly valid but only the 3rd one returns true.
I'm trying to understand if there is anything I've done wrong, or whether there are any issues with the browser (Firefox).
Any ideas?

What about a validation without regexps?
function validateDate(string) {
var parts = string.split("/");
var year = parseInt(parts[2]);
var month = parseInt(parts[1]) - 1;
var day = parseInt(parts[0]);
var date = new Date(year, month, day);
return date.getFullYear() === year && date.getMonth() === month && date.getDate() === day;
}
Demo

You are probably putting these regexes into a string, in which case the "\d" is being translated into a "d".
Try using double slashes: "\\d"
However, I must agree with some of the other suggestions - don't use regex for parsing dates. They aren't really well suited for the job.
For example, you expression would allow '31/02/1985' which is not a date. In particular, you run into problems with leap years (which occur every 4 years except for 3 years within a 400 year time span). Try matching that with a regex!

If you use the constructor new RegExp() you should use the string format :
Example :
var regex = new RegExp(my regex expression is here);
var result = regex.test("(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)[0-9]{2}" ,"ig");
but I don't recommend you to use the constructor try to use this:
result.match(/^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20)[0-9]{2}$/ig);
If not what do you want do with your RegExp ?

You need to use "\\d" instead of "\d".
This repros your problem, with test data:
var regex1 = new RegExp("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\d\d$");
var regex2 = new RegExp("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\d{2}$");
var regex3 = new RegExp("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)[0-9]{2}$");
document.write("<div>1: "+regex1.test("22/11/1982")+"</div>");
document.write("<div>2: "+regex2.test("22/11/1982")+"</div>");
document.write("<div>3: "+regex3.test("22/11/1982")+"</div>");
Output:
1: false
2: false
3: true
This repros the fix:
var regex1 = new RegExp("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\\d\\d$");
var regex2 = new RegExp("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)\\d{2}$");
var regex3 = new RegExp("^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)[0-9]{2}$");
document.write("<div>1: "+regex1.test("22/11/1982")+"</div>");
document.write("<div>2: "+regex2.test("22/11/1982")+"</div>");
document.write("<div>3: "+regex3.test("22/11/1982")+"</div>");
Output:
1: true
2: true
3: true

Try escaping forward slash
Eg : ^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20)\d{2}$

Related

How can I remove the leading two digits from year in Date in javascript?

How can I remove the leading two digits from the year in the format 08/07/2018 in JavaScript? I just want to display 08/07/18.
You can use String.slice.
var dateStr = '19/02/2008';
var output = dateStr.slice(0, 6) + dateStr.slice(8);
console.log(output);
If its a string you could do "1990".substr(2) else you get the year from date object and do the same thing.
Also please always share your solution always. It would be really appreciated if you share what you have done.
Here is the code to remove the first two digits:
var myString = "1990";
var newString = myString.substr(2);
//output:
//myString = 90

search a regex and filter it

Hi i am try to find a variable date in a string with a regex and after this i want to save the date in a new variable my code looks like:
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
if(valide.test(text) === true){
}
how can i put the found date (02.02.1989) in a new variable
You can create groups in your Regex expression (just put the values you want between parenthesis) and then use this to get the specific group value.
Note, however, I think your regex is wrong... it seems you end with 1 plus 4 digits
You can use match on a string:
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
console.dir(text.match(valide)) // ["02.02.1989"]
if(valide.test(text) === true){
}
Using REGEXP function match you can extract the part that match your regular expression.
After this you will get an object. In this case i turn it into a string so you can do a lot more things with it.
var myDate = text.match(valide).toString();
Hope this helps :>
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
if(valide.test(text) === true){
var myDate = text.match(valide).toString();
console.log(myDate)
}
You can use match for that:
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
var foundDate = text.match(valide);
console.log(foundDate);
Also, you can make the regex a bit simpler if you switch the ([./-]) to ([-.]), because - is considered a literal match if it comes first inside a character class.
You could do something like this.
var result = text.match(valide)
Here is a reference for the match method String.prototype.match

How can I replace a specific part of a string?

The string looks like 2017-08-01T00:00:00.000Z
I want to keep the date 2017-08-01, I would prevent to work with replaceAT!
date.replace(date.substr(date.indexOf("T00")),"");
// I also tried RegExp like +"/g"
var d = new Date('2017-08-01T00:00:00.000Z');
d.getFullYear(); // 2017
d.getMonth() + 1; // 8
d.getDate(); // 1
What about this
"2017-08-01T00:00:00.000Z".split("T00")[0]
Use regex expression /T.*$/ - see demo below:
console.log("2017-08-01T00:00:00.000Z".replace(/T.*$/,''));
Why not just use substring()?
var date = date.substring(0,10)
If i understand you correct, a way like this should be right...
var str = '2017-08-01T00:00:00.000Z';
alert(str.substr(0, 10));
If you only want the first part of the string, you can use slice, substr or substring:
var date = "2017-08-01T00:00:00.000Z";
var part = date.slice(0,10);
// or date.substr(0,10);
// or date.substring(0,10);

Three Char Month and Culture matching in javascript

I have a multi cultural website, where I allow users to enter values in a dd-MMM-yyyy format. I am able to determine the different values based upon their culture in C# (May, English = May, German = Mai)
the problem I am having is the javascript validation of these months. I am able to build the list of acceptable values:
english:
^Jan$|^Feb$|^Mar$|^Apr$|^May$|^Jun$|^Jul$|^Aug$|^Sep$|^Oct$|^Nov$|^Dec$
German:
^Jan$|^Feb$|^Mrz$|^Apr$|^Mai$|^Jun$|^Jul$|^Aug$|^Sep$|^Okt$|^Nov$|^Dez$
I just want to make this regular expression case insensitive. but all the references I see are all pointing me to the /gi flag, but I all of the examples make no sense. I have tried the following and it just doesn't work:
var shouldMatch = "may";
var regexPattern = "^Jan$|^Feb$|^Mar$|^Apr$|^May$|^Jun$|^Jul$|^Aug$|^Sep$|^Oct$|^Nov$|^Dec$/gi"
if(shouldMatch.match(regexPattern) != null) {
//this should happen
}
What am I doing wrong? the regex help out there for javascript is killing me.
jsFiddle Demo
But what about trying to match "mAR" or "MAr", etc.? This quickly becomes an interesting scenario. In my opinion, an easy way to do this is to just match to upper case
var shouldMatch = "May";
var regexPattern = "^JAN$|^FEB$|^MAR$|^APR$|^MAY$|^JUN$|^JUL$|^AUG$|^SEP$|^OCT$|^NOV$|^DEC$";
if(shouldMatch.toUpperCase().match(regexPattern) != null) {
alert("match");
}
regexPattern is a string, not a regular expression.
Convert it to a RegExp before you use it with match:
var regexPattern = new RegExp("^JAN$|^FEB$|^MAR$|^APR$|^MAY$|^JUN$|^JUL$|^AUG$|^SEP$|^OCT$|^NOV$|^DEC$", "gi");
And also, convert the shouldMatch to upper case before you use it:
shouldMatch = shouldMatch.toUpperCase();
Your regular expression should not be a string:
var shouldMatch = "may";
var regexPattern = /^Jan$|^Feb$|^Mar$|^Apr$|^May$|^Jun$|^Jul$|^Aug$|^Sep$|^Oct$|^Nov$|^Dec$/i;
if(shouldMatch.match(regexPattern) != null) {
// this seems happened
}
This should work for you.
Changed to using test
No need for the global "g" flag as you are testing the whole string from beginning "^" to end "$"
Changed string regexPattern into a RegExp object
The "i" flag is needed because you want case insensitive.
Javascript
var shouldMatch = "may";
var regexPattern = /^Jan$|^Feb$|^Mar$|^Apr$|^May$|^Jun$|^Jul$|^Aug$|^Sep$|^Oct$|^Nov$|^Dec$/i;
if(regexPattern.test(shouldMatch)) {
alert(shouldMatch);
}
On jsfiddle
You could also make it a little shorter and a little less ugly by doing this
var regexPattern = /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$/i;
On jsfiddle
As an alternative to regex, you could also use String.indexOf and Array.some, and try each pattern to see if it is in the string you are testing. This example will require a modern browser or a "shim"/"polyfill" for older browsers. You could also check equality "===" if you want to match the whole string rather than see if it is contained in.
Javascript
var shouldMatch = "may";
var patterns = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec".split("|");
var matched = patterns.some(function (pattern) {
if (shouldMatch.toLowerCase().indexOf(pattern.toLowerCase()) !== -1) {
alert(shouldMatch);
return true;
}
return false;
});
On jsfiddle
Or run the possibilities together-
var Rx=/^(jan|feb|m(ar|rz)|apr|ma[iy]|jun|jul|aug|sep|o[ck]t|nov|de[cz])$/i
Rx.test('may');

How to split an array index

how to split an array index i.e.. sample code
var parts = currentVal.split(" ");
var datePart = parts.splice(0,1);
alert("Date: " + datePart );
var timePart = parts.join(' ');
here i am validating the date time regular expression. var datePart is an array index, now i want to split datepart ....
var parts1 = datePart.split('/');
parts1.date = parseInt(parts1[0]);
parts1.month = parseInt(parts1[1]);
parts1.year = parseInt(parts1[2]);
but it is showing uncaught type error, their is no method split(); Can any one help me how do i separate date, month, year.
If you're trying to just check whether a string represents a valid date or not, I would personally recommend the magical Date object that javascript natively supports. Through some sort of wizardry it can read the date in almost any format you throw at it, and if it is an invalid date it will evaluate to the string Invalid Date.
So to check if currentVal is a valid date, do:
if (new Date(currentVal) == 'Invalid Date') {
... // The date is invalid
} else {
... // The date is valid
}
On the other hand, if you need to use a specific regex to validate the date, you could either do something like
var parts = currentVal.split(' ');
var dateParts = parts[0].split('/');
var timePart = parts[1]; // Maybe you want to split this as well?
And this would leave dateParts as an array containing the month, day and year.
I think you are looking for the function explode().
http://php.net/manual/en/function.explode.php
Actually function splice returns an array of removed elements, so to solve you problem you just need to apply split on the first element of datePart array:
var parts1 = datePart[0].split("/");

Categories