Skip to content

Instantly share code, notes, and snippets.

@akizor
Last active August 29, 2015 14:23
Show Gist options
  • Save akizor/88cac7a3fe71145c4c85 to your computer and use it in GitHub Desktop.
Save akizor/88cac7a3fe71145c4c85 to your computer and use it in GitHub Desktop.
Sweden Personnumber Validator for Magento
/**
* Magento Sweden SSN Validator
* @param none
* @return boolean
* @author Daniel Placinta (daniel@artgames.ro)
* Based on: jquery-validate-personnummer by Sebastian Wallin
* Github: https://github.com/wallin/jquery-validate-personnummer
*/
if(Validation) {
Validation.addAllThese([
[
'validate-sweden-ssn',
'Please add a valid SSN',
function(v,r){
/**
* The Luhn Algorithm
* https://en.wikipedia.org/wiki/Luhn_algorithm
* @param number
* @return number
*/
var luhn = function(number){
var k, sum, v, _i, _len, _ref;
number = "" + number;
sum = 0;
_ref = number.split('');
for (k = _i = 0, _len = _ref.length; _i < _len; k = ++_i) {
v = _ref[k];
v *= 2 - (k % 2);
if (v > 9) {
v -= 9;
}
sum += v;
}
return Math.ceil(sum / 10) * 10 - sum;
}
v = v.trim();
if(Validation.get('IsEmpty').test(v)){
return false;
}
/**
* Personal Identity Number (Sweden) Algorithm
* https://en.wikipedia.org/wiki/Personal_identity_number_%28Sweden%29
*/
var cd, control, day, divider, month, p, serial, year, _ref;
v = "" + v;
p = v.match(/(18|19|20|21){0,1}(\d{2})(\d{2})(\d{2})([\-\+]{0,1})(\d{3})(\d{0,1})/);
if (!p) {
return false;
}
_ref = p.slice(2), year = _ref[0], month = _ref[1], day = _ref[2], divider = _ref[3], serial = _ref[4], control = _ref[5];
cd = luhn("" + year + month + day + serial);
if(cd !== +control || !control){
/* SSN is invalid */
this.error = 'SSN is not valid. Eg: YYMMDD-NNNN (N = number)';
return false;
}
/**
* Additional check
* Verify if user is 20 years (or above) old
*/
/* 20 years */
var yearsToSubstract = 20;
/* create a date object using SSN date parameters*/
var userDate = new Date(year + "/" + month + "/" + day);
/* solve Y2K conversion issue */
userDate.setYear(year);
/* convert to UTC time */
var userDateUTC = new Date(userDate.getUTCFullYear(), userDate.getUTCMonth(), userDate.getUTCDate(), userDate.getUTCHours(), userDate.getUTCMinutes(), userDate.getUTCSeconds());
/* add 20 years to his age */
userDateUTC.setYear(userDate.getUTCFullYear() + yearsToSubstract);
/* check if the new age is above current time */
if(userDateUTC > Date.now()){
/* User does not meet age requirements */
this.error = 'You need to be at least ' + yearsToSubstract + ' years old.';
return false;
}
/* user meets all requirements */
return true;
}
],
[ ]
])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment