Skip to content

Instantly share code, notes, and snippets.

@dmoss18
Created December 11, 2018 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmoss18/f330d4e78e7c56237f35c84450ba07b3 to your computer and use it in GitHub Desktop.
Save dmoss18/f330d4e78e7c56237f35c84450ba07b3 to your computer and use it in GitHub Desktop.
import { parsePhoneNumber } from 'libphonenumber-js'
import { validate, isString } from 'validate.js'
import * as REGEX_PATTERNS from './regex/constants'
import moment from 'moment'
// tslint:disable:no-unsafe-any
export const PHONE_NUMBER = (value: string) => {
const errorMessage = 'is invalid'
if (!!value && isString(value)) {
try {
return parsePhoneNumber(value, 'US').isValid() ? undefined : errorMessage // TODO: International
} catch {
return errorMessage
}
}
return errorMessage
}
export const TAX_NUMBER = (value: string) => {
const errorMessage = 'is invalid'
if (!isString(value)) {
return errorMessage
}
const sanitizedTaxNumber = value.replace(/\D/g, '')
// tslint:disable-next-line:no-magic-numbers
return sanitizedTaxNumber.length === 9 && REGEX_PATTERNS.SSN.test(sanitizedTaxNumber) ?
undefined :
errorMessage
}
const validators: any = (validate as any).validators
if (validators) {
validators.phoneNumber = PHONE_NUMBER
validators.taxNumber = TAX_NUMBER
const extend = (validate as any).extend
if (extend) {
extend(validators.datetime, {
parse(value: any, options: any) {
return +moment(value)
},
format(value: any, options: any) {
const format = options.dateOnly ? 'YYYY-MM-DD' : 'YYYY-MM-DD hh:mm:ss'
return moment(value).format(format)
}
})
}
}
export { validate }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment