Skip to content

Instantly share code, notes, and snippets.

@Miserlou
Created January 29, 2017 02:00
Show Gist options
  • Save Miserlou/5f341c0b7f454929264cf4a7f3da1792 to your computer and use it in GitHub Desktop.
Save Miserlou/5f341c0b7f454929264cf4a7f3da1792 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