Does anyone have a reference for to a javascript reg exp for the date pattern MM / YYYY? I've been researching only to find the usual MM/DD/YYYY, etc.
Asked
Active
Viewed 7,077 times
1
-
5And what is the problem? Just take the part matching "/DD" out. – mishik Jun 27 '13 at 18:41
-
2Reference to JavaScript regex: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions. – Felix Kling Jun 27 '13 at 18:43
5 Answers
6
how about:
This literal here for a regex: /[\d]{2}\/[\d]{4}/
alternatively it looks like you're wanting space between the m and ys so:
/[\d]{2} \/ [\d]{4}/

bluetoft
- 5,373
- 2
- 23
- 26
-
-
1You don't need `[]` if you're only matching `\d`. The question actually has spaces around the `/`. – Paul S. Jun 27 '13 at 18:46
-
-
Indeed I should have added the ^ to the beginning to ensure an exact match `/^[\d]{2}\/[\d]{4}/` – bluetoft Jun 27 '13 at 18:59
-
1@Ben Be careful with this solution. It allows months 13-99. Check out dav's solution so your month is 1-12. – Shaz Jun 27 '13 at 19:03
-
I'm using this with DOJO and had to mash some stuff so the final was ^([0-2][0-9]\/(19|20)[0-9]{2})$... dojo for some reason doesn't like [/d] – bntrns Jun 27 '13 at 19:05
5
(0?[1-9]|1[0-2])\/(\d{4})
This ensures you get a valid month, whether it be two or one digits. I'm assuming you don't want to restrict the year.

dav
- 1,211
- 1
- 13
- 19
0
Simply remove the part of the regex that matches the day (DD). In this similar post, the answer
function parseDate(str) {
var m = str.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/);
return (m) ? new Date(m[3], m[2]-1, m[1]) : null;
}
was given. Just edit the regex slightly to remove one of the 2 decimal matches, and you get the function
var m = str.match(/^(\d{1,2})\/(\d{4})$/);

Community
- 1
- 1

Eric Palace
- 322
- 2
- 14
0
You don't need to use regex for this
var date=input.split("/");
var month=parseInt(date[0],10);
var year=parseInt(date[1],10);
if(isNaN(month) || isNaN(year))//invalid string
else //check if month and year is valid
parseInt
would evaluate to NaN
incase the format is not proper.So,in a way you are validating the string
If you want regex
^\d{2}/\d{4}$

Anirudha
- 32,393
- 7
- 68
- 89
-
2
-
-
-
@Anirudh The question was in the form of 'How can I do this with regex?' and you answered in the form of 'Here's a solution that doesn't use regex'. It's not an argument of whether your solution finds a valid month and year, it's an argument of not satisfying the requirements of the question. – Shaz Jun 27 '13 at 18:55
-
@RyanWH still he would have to individually check if month and year is valid by parsing it to int..there is no need of regex – Anirudha Jun 27 '13 at 19:03
-
@Anirudh You can't be sure of that, as you don't know his entire problem. If he was wanting a regex to simply detect if there's a month and a year, he could use dav's solution. dav's solution allows a leading zero on the month and only allows 1-12. No parsing is required. – Shaz Jun 27 '13 at 19:06