Skip to content

Instantly share code, notes, and snippets.

@nekman
Created July 1, 2011 09:33
Show Gist options
  • Save nekman/1058171 to your computer and use it in GitHub Desktop.
Save nekman/1058171 to your computer and use it in GitHub Desktop.
Simple JS regexp for swedish social security number
/*NOTE:
This is just a simple pattern check, so: /^\d{6,8}[-|(\s)]{0,1}\d{4}$/.test("000000 0000") // true
/^\d{6,8}[-|(\s)]{0,1}\d{4}$/.test('195505055555'); // true
/^\d{6,8}[-|(\s)]{0,1}\d{4}$/.test('19550505-5555'); // true
/^\d{6,8}[-|(\s)]{0,1}\d{4}$/.test('550505-5555'); // true
/^\d{6,8}[-|(\s)]{0,1}\d{4}$/.test('550505 5555'); // true
/^\d{6,8}[-|(\s)]{0,1}\d{4}$/.test('5505055555'); // true
*/
//JS
var isSwedishSocialSecurityNumber = function(str) {
return /^\d{6,8}[-|(\s)]{0,1}\d{4}$/.test(str);
};
//Dojo
(function($) {
$.mixin($, {
isSwedishSocialSecurityNumber : function(str) {
return /^\d{6,8}[-|(\s)]{0,1}\d{4}$/.test(str);
}
});
})(dojo);
//dojo.isSwedishSocialSecurityNumber('195505055555');
//jQuery
(function($) {
$.extend({
isSwedishSocialSecurityNumber : function(str) {
return /^\d{6,8}[-|(\s)]{0,1}\d{4}$/.test(str);
}
});
})(jQuery);
//jQuery.isSwedishSocialSecurityNumber('195505055555');
@ShadOoW
Copy link

ShadOoW commented Aug 24, 2019

I have another improvement to add:
/^(19|20)?(\d{6}([-+]|\s)\d{4}|(?!19|20)\d{10})$/

I added the possibility to use a + instead of - because this can be used for numbers older than 100 years.

Somebody was on Wikipedia before googling :D good job!

@nekman
Copy link
Author

nekman commented Aug 24, 2019

I have totally missed all these comments! Fun that an old gist from 2011 (!) was used by someone else than me :)

@Pianotehead
Copy link

Pianotehead commented Sep 12, 2020

Don't know if the OP or anyone will read this, but this is my version, and it seems to work!

^(19|20)?\d{2}(01|02|03|04|05|06|07|08|09|10|11|12)((0[1-9])|(1|2)[0-9]|(30|31))-\d{4}$

The problem with the expressions so far, is that they don't validate the date, after the year part. So an SSN like 852240-1010 gives a match, but we all know, nobody can be born in the 22th month, and on the 40th day of the year.

I'm studying to become a web developer in C# .NET, and our assignment was to create an app to calculate the age of a person with a Swedish social security number. I wanted to validate the SSN, so that DateTime objects wouldn't throw an exception.

You can see my solution in my repositories, where I use the above regular expression. I know, it is overly complicated, but I haven't found a way to simplify it, wish I would!

@boltgolt
Copy link

Watch out with the regex above me! It's true that "nobody can be born in the 22th month" but in some edge cases skatteverket uses numbers with these invalid dates

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment