Monday, October 30, 2006

JavaScript parent / child communication example

In a test I was running, I needed a valid date of birth in mm/dd/yyyy format. Here is the solution I came up with:


${__javaScript(with(new Date()) dob = String(Math.floor(Math.random() * 12) + 101).substr(1) + '/' + String(Math.floor(Math.random() * 28) + 101).substr(1) + '/' + String(getFullYear() - Math.floor(Math.random() * 99) - 1), dateString)}

The plain JavaScript version is


with(new Date()) dob = String(Math.floor(Math.random() * 12) + 101).substr(1) + '/' + String(Math.floor(Math.random() * 28) + 101).substr(1) + '/' + String(getFullYear() - Math.floor(Math.random() * 99) -1 ); alert(dob);

The first part gives us a zero padded month from 01-12. The second part gives a zero padded day from 01-28 (I did not want to deal with leap years and end-of month guessing for this test). The final part subtracts 1 to 100 from the current year (guaranteeing no future dates in the current year). Quick and dirty -- Enjoy!