1 import { c, msgid } from 'ttag';
3 import { MIN_PASSWORD_LENGTH } from '../constants';
4 import { validateEmailAddress } from './email';
5 import { REGEX_USERNAME, REGEX_USERNAME_END, REGEX_USERNAME_START, isNumber } from './validators';
7 export const requiredValidator = (value: any) =>
8 value === undefined || value === null || value?.trim?.() === '' ? c('Error').t`This field is required` : '';
10 export const usernameCharacterValidator = (value: string) =>
11 !REGEX_USERNAME.test(value) ? c('Error').t`Try using only letters, numerals, and _.-` : '';
13 export const usernameStartCharacterValidator = (value: string) =>
14 !REGEX_USERNAME_START.test(value) ? c('Error').t`Username must begin with a letter or digit` : '';
16 export const usernameEndCharacterValidator = (value: string) =>
17 !REGEX_USERNAME_END.test(value) ? c('Error').t`Username must end with a letter or digit` : '';
19 const defaultUsernameLength = 40;
20 export const usernameLengthValidator = (value: string, n = defaultUsernameLength) =>
21 value.length > defaultUsernameLength
22 ? c('Validation').ngettext(
23 msgid`Try a shorter username (${n} character max)`,
24 `Try a shorter username (${n} characters max)`,
29 export const minLengthValidator = (value: string, minimumLength: number) =>
30 value.length < minimumLength ? c('Error').t`This field requires a minimum of ${minimumLength} characters.` : '';
32 export const maxLengthValidator = (value: string, maximumLength: number) =>
33 value.length > maximumLength ? c('Error').t`This field exceeds the maximum of ${maximumLength} characters.` : '';
35 export const emailValidator = (value: string) => (!validateEmailAddress(value) ? c('Error').t`Email is not valid` : '');
37 export const numberValidator = (value: string) => (!isNumber(value) ? c('Error').t`Not a valid number` : '');
39 export const confirmPasswordValidator = (a: string, b: string) => (a !== b ? c('Error').t`Passwords do not match` : '');
41 export const confirmEmailValidator = (a: string, b: string) =>
42 a !== b ? c('Error').t`The email addresses do not match` : '';
43 export const usernameValidator = (a: string, b: string) => (a !== b ? c('Error').t`Incorrect username` : '');
45 export const getMinPasswordLengthMessage = () =>
46 c('Validation').ngettext(
47 msgid`Password must contain at least ${MIN_PASSWORD_LENGTH} character`,
48 `Password must contain at least ${MIN_PASSWORD_LENGTH} characters`,
52 export const passwordLengthValidator = (password: string) =>
53 password.length < MIN_PASSWORD_LENGTH ? getMinPasswordLengthMessage() : '';