Created
December 11, 2018 19:29
-
-
Save dmoss18/f330d4e78e7c56237f35c84450ba07b3 to your computer and use it in GitHub Desktop.
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
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