Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Common Swedish validation in Javascript
/***************** POSTAL CODE *****************/
// cannot start with a zero and must contain 5 digits.
let postalCode = "12345";
let regexPostalCode = new RegExp("^[1-9][0-9]{4}$");
let postalCodeMathces = postalcode.match(regexPostalCode);
console.log('POSTAL CODE MATCHES:', postalCodeMathces !== null);
/***************** PERSONAL NUMBER *****************/
// can only start with one or two
// second character can only be a nine or zero
// ninth character is an optional hyphen (-)
// can not be contain more than twelve digits plus an optional hyphen (-)
let personalNumber = "1998121212-1234";
let regexPersonalNumber = new RegExp("^[12]{1}[90]{1}[0-9]{6}(-)?[0-9]{4}$");
let personalNumberMatches = personalNumber.match(regexPersonalNumber);
console.log('PERSONAL NUMBER MATCHES:', personalNumberMatches !== null);
/***************** EMAIL ADDRESS *****************/
let emailAddress = "name@gmail.se";
let regexEmailAddress = new RegExp("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
let emailAddressMatches = emailAddress.match(regexEmailAddress);
console.log('EMAIL ADDRESS MATCHES:', emailAddressMatches !== null);
/***************** PHONE NUMBER *****************/
let phoneNumber = "073-1234567";
let regexPhoneNumber = new RegExp("^08-[0-9]{6,8}$|^0[1-9][0-9]-[0-9]{5,7}$|^0[1-9][0-9]{2}-[0-9]{5,6}$|^0[1-9][0-9]{6,8}$");
let phoneNumberMatches = phoneNumber.match(regexPhoneNumber);
console.log('PHONE NUMBER MATCHES:', phoneNumberMatches !== null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment