UNPKG

yup-phone-js

Version:
46 lines (35 loc) 1.41 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var Yup = require('yup'); var libphonenumberJs = require('libphonenumber-js'); function validatePhone(value, options) { if (typeof value !== "string") { return false; } try { var parseCountry = options.validCountries && !Array.isArray(options.validCountries) ? options.validCountries : undefined; var phoneNumber = libphonenumberJs.parsePhoneNumber(value, parseCountry); if (!phoneNumber.isPossible()) { return false; } if (options.validCountries) { var validCountries = Array.isArray(options.validCountries) ? options.validCountries : [options.validCountries]; if (!phoneNumber.country || !validCountries.includes(phoneNumber.country)) { return false; } } return !options.strictValidation || phoneNumber.isValid(); } catch (e) { console.warn("Error validating phone number:", e); return false; } } var PHONE_TEST_NAME = "phone"; Yup.addMethod(Yup.string, PHONE_TEST_NAME, function yupPhone(options, errorMessage) { var errMsg = errorMessage != null ? errorMessage : "${path} must be a valid phone number."; return this.test(PHONE_TEST_NAME, errMsg, function (value) { return validatePhone(value, options != null ? options : {}); }); }); exports.validatePhone = validatePhone; //# sourceMappingURL=yup-phone-js.cjs.development.js.map