How to validate date for MM/YY in javascript?
11,345
Solution 1
Try this simple function.
function validDate(dValue) {
var result = false;
dValue = dValue.split('/');
var pattern = /^\d{2}$/;
if (dValue[0] < 1 || dValue[0] > 12)
result = true;
if (!pattern.test(dValue[0]) || !pattern.test(dValue[1]))
result = true;
if (dValue[2])
result = true;
if (result) alert("Please enter a valid date in MM/YY format.");
}
Solution 2
You could use a regular expression;
var s = "11/12";
/^(0[1-9]|1[0-2])\/\d{2}$/.test(s);
The first part, (0[1-9]|1[0-2])
, validates the month part, i.e., that the value is in the range 01-12
. The second part, \d{2}
validates the two-digit year.
Related videos on Youtube
Comments
-
Harshal Mahajan over 1 year
Possible Duplicate:
Formatting a date in JavaScriptI have a form having lots of fields and all are validate through Java-script and one of them is for date.
<td>Credit Card Expiration Date</td><td>:<input class="input" type="text" name="CC_expiration_date" id="CC_expiration_date"><p>(MM/YY)</p></td>
Now I want that the user must enter the date in (MM/YY) format. How could I validate this using JavaScript?
I tried to make a regular expression:
/^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
... but didnt work.
-
Vinay over 11 yearsit wont validate if month is greater than 12. fix it.
-
Harshal Mahajan over 11 years@viany ,can you please change the regular expression coz it doesn't give error if i type 12/12/2012
-
Harshal Mahajan over 11 yearsit gives error msg while i entering the valid date 12/12
-
Harshal Mahajan over 11 yearsit gives error msg while i entering the valid date 12/12
-
João Silva over 11 yearsAre you sure the string is exactly
12/12
. Try/^(0[1-9]|1[0-2])\/\d{2}$/.test("12/12")
. It returnstrue
. -
Harshal Mahajan over 11 yearsstill not working ,not giving any error on ri8 or wrong value.
-
Vinay over 11 years@HarshalMahajan As your question says you want to validate only MM/YY format. if you want to validate it for DD/MM/YYYY, you can use same answer with some formating.
-
Harshal Mahajan over 11 yearsactually i want that the user should enter the date like 12/12 not like 12/12/2012,and if he does than there should error MSG.you answer works fine for 12/12 but it doesn't validate for 12/12/2012
-
Vinay over 11 years@HarshalMahajan Ok. updated accordingly.
-
Clyde Lobo over 11 yearsIt works jsfiddle.net/TqwVb