Magento – Age verification. Varien.DateElement vs Varien.DOB

javascriptmagento-1.6validation

I try to add a age verification to the day of birth field on the registration page.
For now I added this code to the Varien.DateElement validate function in the js\varien\js.js file:

today = new Date();
var dateLegal = new Date(today.getFullYear() - 18, today.getMonth(), today.getDate() );
console.log(dateLegal);
if (test.valueOf() > dateLegal.valueOf()) {
    error = 'You must be 18.......';
}

This works how I want it. The problem I have with this is, Varien.DateElement is for every date fields. There is a Varien.DOB special for day of birth. I tried to add there a validate function, but it will be never called.

Varien.DOB = Class.create();
Varien.DOB.prototype = {
    initialize: function(selector, required, format) {
        var el = $$(selector)[0];
        var container       = {};
        container.day       = Element.select(el, '.dob-day input')[0];
        container.month     = Element.select(el, '.dob-month input')[0];
        container.year      = Element.select(el, '.dob-year input')[0];
        container.full      = Element.select(el, '.dob-full input')[0];
        container.advice    = Element.select(el, '.validation-advice')[0];

        new Varien.DateElement('container', container, required, format);
    },
    validate: function() {
        var error = false;
       console.log("validate called"); //I will never be called
    }
};

So is there a better way to add a validation then to place it in Varien.DateElement ?

Best Answer

Please check out this excellent post on creating a custom validation. Adding a second type of validation is cleaner as it doesn't require you to edit existing code.

In your case it would be something like

Validation.add('validate-dob-18','You are not 18',function(value){
   [...]
   calculate nr of years
   [...]
   if(years > 18)
   {
      return true;
   }
   return false;
});

I would suggest also adding PHP validation as Javascript validation as anything but secure.

Also, to work more easily with dates and times check out momentjs.

Related Topic