Created
January 29, 2017 02:00
-
-
Save Miserlou/5f341c0b7f454929264cf4a7f3da1792 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