use-input-validator.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { useCallback } from 'react';
  2. import { useTranslation } from 'next-i18next';
  3. export const AlertType = {
  4. WARNING: 'Warning',
  5. ERROR: 'Error',
  6. } as const;
  7. export type AlertType = typeof AlertType[keyof typeof AlertType];
  8. export const ValidationTarget = {
  9. FOLDER: 'folder_name',
  10. PAGE: 'page_name',
  11. DEFAULT: 'field',
  12. };
  13. export type ValidationTarget = typeof ValidationTarget[keyof typeof ValidationTarget];
  14. export type AlertInfo = {
  15. type?: AlertType
  16. message?: string,
  17. target?: string
  18. }
  19. export type InputValidationResult = {
  20. type: AlertType
  21. typeLabel: string,
  22. message: string,
  23. target: string
  24. }
  25. export type InputValidator = (input?: string, alertType?: AlertType) => InputValidationResult | void;
  26. export const useInputValidator = (validationTarget: ValidationTarget = ValidationTarget.DEFAULT): InputValidator => {
  27. const { t } = useTranslation();
  28. const inputValidator: InputValidator = useCallback((input?, alertType = AlertType.WARNING) => {
  29. if ((input ?? '').trim() === '') {
  30. return {
  31. target: validationTarget,
  32. type: alertType,
  33. typeLabel: t(alertType),
  34. message: t(
  35. 'input_validation.message.field_required',
  36. { target: t(`input_validation.target.${validationTarget}`) },
  37. ),
  38. };
  39. }
  40. return;
  41. }, [t, validationTarget]);
  42. return inputValidator;
  43. };