Accéder au contenu principal

Articles

Affichage des articles du septembre, 2013

Date format matching regex

Regex is a must-learn for any programmer, plus it is always interesting to see how an apparently complex check can be done with a basic rule (...or how a simple check sometimes requires a long and obscure rule, but that's the whole fun of it :P). Here's a short and useful regex to match a date field (for instance when submitting a form). // expected field value format: YYYY-MM-DD var e = document.getElementById("myDateField").value; var m = e.match(/(20\d\d|19\d\d)\-(0\d|1[012])\-([012]\d|3[01])/); Breaking it down: / (20\d\d|19\d\d) \- (0\d|1[012]) \- ([012]\d|3[01]) / 1. Year (20\d\d|19\d\d) Trying to match either "20" followed by 2 digits (2000, 2001,2002,...2099) or "19" and then 2 digits (1900...1999). Would not match: 20a0, 201, 20AA 2. Month (0\d|1[012]) Trying to match either "0" followed by one digit (01...09) or "1" followed by 0, 1 or 2 (hence only 10,11 or 12). We assume here that the month must