Files
freeCodeCamp/utils/validate.ts
Oliver Eyton-Williams 4ff00922da refactor: fix hidden eslint errors (#49365)
* refactor: explicit types for validate

* refactor: explicit return types for ui-components

* refactor: use exec instead of match

* refactor: add lots more boundary types

* refactor: more eslint warnings

* refactor: more explicit exports

* refactor: more explicit types

* refactor: even more explicit types

* fix: relax type contrainsts for superblock-order

* refactor: final boundaries

* refactor: avoid using 'object' type

* fix: use named import for captureException

This uses TypeScript (which works) instead of import/namespace
(which doesn't) to check if captureException exists in sentry/gatsby
(it does)
2023-02-13 07:13:50 -08:00

39 lines
961 B
TypeScript

type Valid = {
valid: true;
error: null;
};
type Invalid = {
valid: false;
error: string;
};
type Validated = Valid | Invalid;
export const invalidCharError: Invalid = {
valid: false,
error: 'contains invalid characters'
};
export const validationSuccess: Valid = { valid: true, error: null };
export const usernameTooShort: Invalid = {
valid: false,
error: 'is too short'
};
export const usernameIsHttpStatusCode: Invalid = {
valid: false,
error: 'is a reserved error code'
};
const validCharsRE = /^[a-zA-Z0-9\-_+]*$/;
export const isHttpStatusCode = (str: string): boolean => {
const output = parseInt(str, 10);
return !isNaN(output) && output >= 100 && output <= 599;
};
export const isValidUsername = (str: string): Validated => {
if (!validCharsRE.test(str)) return invalidCharError;
if (str.length < 3) return usernameTooShort;
if (isHttpStatusCode(str)) return usernameIsHttpStatusCode;
return validationSuccess;
};