(options: StringValidationOptions)
| 34 | * conditions. |
| 35 | */ |
| 36 | export const stringValidateFn = (options: StringValidationOptions): ValidateFunction<string> => { |
| 37 | if ('regex' in options) { |
| 38 | return (input: string): true | string => { |
| 39 | const regex = typeof options.regex === 'string' ? new RegExp(options.regex) : options.regex |
| 40 | return regex.test(input) || (options.errorMessage ?? `must match regex ${regex}`) |
| 41 | } |
| 42 | } |
| 43 | if ('minLength' in options && 'maxLength' in options && options.minLength > options.maxLength) { |
| 44 | throw Error('maxLength must be >= minLength') |
| 45 | } |
| 46 | return (input: string): true | string => { |
| 47 | if ('minLength' in options && input.length < options.minLength) { |
| 48 | return `must be at least ${options.minLength} characters` |
| 49 | } |
| 50 | if ('maxLength' in options && input.length > options.maxLength) { |
| 51 | return `must be no more than ${options.maxLength} characters` |
| 52 | } |
| 53 | return true |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | export type NumberValidateOptions = { |
| 58 | min?: number |
no outgoing calls
no test coverage detected