Skip to content

Instantly share code, notes, and snippets.

@kevinmamaqi
Last active May 29, 2019 12:25
Show Gist options
  • Save kevinmamaqi/89efb1f33e52bb389d6fc2f04c356ed0 to your computer and use it in GitHub Desktop.
Save kevinmamaqi/89efb1f33e52bb389d6fc2f04c356ed0 to your computer and use it in GitHub Desktop.
Handy JS regex validation functions for email, name and website fields.
// Source: https://stackoverflow.com/questions/46155/how-to-validate-an-email-address-in-javascript
function validateEmail(id) {
var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;
var ctrl = document.getElementById(id);
if (regex.test(ctrl.value)) {
return true;
}
else {
return false;
}
}
// Source: https://stackoverflow.com/questions/20690499/concrete-javascript-regex-for-accented-characters-diacritics
function validateName(id) {
var regex = /^[a-zA-Z\u00C0-\u024F\u1E00-\u1EFF]{3,50}$/;
var ctrl = document.getElementById(id);
if (regex.test(ctrl.value)) {
return true;
}
else {
return false;
}
}
// Source: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url
function validateWebsite(id) {
var regex = /(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/;
var ctrl = document.getElementById(id);
// To allow if empty: if (regex.test(ctrl.value) || ctrl.value === "")
if (regex.test(ctrl.value)) {
return true;
}
else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment