-
-
Save johnteee/237d799837918620ba69e8ac36fdf34d to your computer and use it in GitHub Desktop.
Validating a US (or international) phone number with Parsley and libphonenumber-js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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