2

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.

Community
  • 1
  • 1
Harshal
  • 3,562
  • 9
  • 36
  • 65

4 Answers4

4

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.

João Silva
  • 89,303
  • 29
  • 152
  • 158
4

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.");
}
Vinay
  • 2,564
  • 4
  • 26
  • 35
  • @viany ,can you please change the regular expression coz it doesn't give error if i type 12/12/2012 – Harshal Sep 11 '12 at 11:25
  • @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. – Vinay Sep 11 '12 at 11:56
  • 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 – Harshal Sep 11 '12 at 11:58
  • @HarshalMahajan Ok. updated accordingly. – Vinay Sep 11 '12 at 12:26
0

Try this..

For DD-MM-YYYY ==> var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/

For MM-YY ==> var dateReg = /^\d{2}[./-]\d{2}$/

Know about regex.. http://docs.oracle.com/javase/tutorial/essential/regex/char_classes.html

More Details Click Here

Community
  • 1
  • 1
Basith
  • 1,077
  • 7
  • 22
0
var d = "09/11"
var pattern = /^(0[1-9]|1[012])\/\d{2}$/
pattern.test(d)
Clyde Lobo
  • 9,126
  • 7
  • 34
  • 61