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.

Share:
11,345

Related videos on Youtube

Harshal Mahajan
Author by

Harshal Mahajan

The Developer...!!

Updated on September 10, 2022

Comments

  • Harshal Mahajan
    Harshal Mahajan over 1 year

    Possible Duplicate:
    Formatting a date in JavaScript

    I 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
    Vinay over 11 years
    it wont validate if month is greater than 12. fix it.
  • Harshal Mahajan
    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
    Harshal Mahajan over 11 years
    it gives error msg while i entering the valid date 12/12
  • Harshal Mahajan
    Harshal Mahajan over 11 years
    it gives error msg while i entering the valid date 12/12
  • João Silva
    João Silva over 11 years
    Are you sure the string is exactly 12/12. Try /^(0[1-9]|1[0-2])\/\d{2}$/.test("12/12"). It returns true.
  • Harshal Mahajan
    Harshal Mahajan over 11 years
    still not working ,not giving any error on ri8 or wrong value.
  • Vinay
    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
    Harshal Mahajan over 11 years
    actually 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
    Vinay over 11 years
    @HarshalMahajan Ok. updated accordingly.
  • Clyde Lobo
    Clyde Lobo over 11 years