Skip to content

Instantly share code, notes, and snippets.

@johnteee
Forked from Miserlou/ustel.html
Created March 8, 2018 13:15
Show Gist options
  • Save johnteee/237d799837918620ba69e8ac36fdf34d to your computer and use it in GitHub Desktop.
Save johnteee/237d799837918620ba69e8ac36fdf34d to your computer and use it in GitHub Desktop.
Validating a US (or international) phone number with Parsley and libphonenumber-js
<!-- requirements -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.6.2/parsley.min.js"></script>
<script src="https://halt-hammerzeit.github.io/libphonenumber-js/libphonenumber-js.min.js"></script>
<!-- custom validator -->
<script type="text/javascript">
$(document).ready(function() {
window.Parsley.addValidator('ustel', {
requirementType: 'string',
validateString: function(value) {
var parsed = libphonenumber.parse(value, 'US'); // Change 'US' if you must.
if ('phone' in parsed){
return true;
} else {
return false;
}
},
messages: {
en: 'Please enter a US phone number'
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment