Skip to content

Instantly share code, notes, and snippets.

@guillefd
Created February 3, 2018 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guillefd/756871831fb1489c1112d5b0d9bee0b9 to your computer and use it in GitHub Desktop.
Save guillefd/756871831fb1489c1112d5b0d9bee0b9 to your computer and use it in GitHub Desktop.
JS Regex Validations
function isInputValid(value, type) {
let valid;
let errorTxt;
switch(type) {
case 'email':
valid = /^(([^<>()\[\]\\.,;:\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,}))$/.test(value);
errorTxt = 'Enter a valida email';
break;
case 'phone':
valid = /^([-0-9.()+ ]{5,50})*$/.test(value);
errorTxt = 'Enter only numbers and/or any of this chars: _-.()';
break;
case 'url':
valid = /(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/igm.test(value);
errorTxt = 'Enter a valid URL';
break;
case 'user':
valid = /^[-a-zA-Z0-9+.@_]*$/.test(value);
errorTxt = 'Enter only alphanumerics and any of this chars: _-.@|';
break;
}
return valid;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment