Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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