Skip to content

Instantly share code, notes, and snippets.

@pieterbeulque
Created July 29, 2015 12:51
Show Gist options
  • Save pieterbeulque/3b7da95cad6a09050969 to your computer and use it in GitHub Desktop.
Save pieterbeulque/3b7da95cad6a09050969 to your computer and use it in GitHub Desktop.
Validating stuff in JS
window.validate = window.validate || {};
window.validate.date = function (raw) {
var date, parsed;
date = raw.split(/[\D]+/);
if (date.length !== 3 || date[0].length > 2 || date[1].length > 2 || (date[2].length !== 2 && date[2].length !== 4)) {
return false;
}
date[0] = (date[0].length === 1) ? '0' + date[0] : date[0];
date[1] = (date[1].length === 1) ? '0' + date[1] : date[1];
date[2] = (date[2].length === 2) ? '19' + date[2] : date[2];
if (!!window.moment) {
parsed = window.moment([parseInt(date[2], 10), parseInt(date[1], 10), parseInt(date[0], 10)]);
if (!parsed.isValid() && parsed.diff(window.moment(), 'years') > -3 && parsed.diff(window.moment(), 'years') < -100) {
return false;
}
}
date = date.join('/');
if (!date.match(/^[\d]{2}\/[\d]{2}\/[\d]{4}$/)) {
return false;
}
return date;
};
window.validate.email = function (email) {
if (!!email.toString().match(/^[^@^\s]+@[^@^\s]+\.[^@]+$/)) {
return email.toLowerCase().replace(/\s+/gi, '');
}
return false;
};
window.validate.phone = function (phone) {
phone = phone.replace(/\s+/gi, '');
if (phone.length === 0) {
return false;
}
if (phone.length < 6) {
return false;
}
// Formatting
// 1. Replace all separators with spaces
tel = tel.replace(/[^\d\+\(\)]+/gi, ' ');
// 2. Replace +32(0)34 with +32 (0) 34 (note the space)
tel = tel.replace(/(\S)(\()/, '$1 (');
tel = tel.replace(/(\))(\S)/, ') $2');
if (tel[0] === '0') {
return tel;
} else if (tel[0] === '+') {
// Formatting: replace +32479 with +32 479 (note the space)
return tel.replace(/^(\+[\d]{2})(\S)/, '$1 $2');
}
return false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment