TypeAssert.ts 942 B

12345678910111213141516171819202122232425262728293031323334
  1. import type { AssertRule } from '~/types/interfaces'
  2. import { useI18n } from 'vue-i18n'
  3. import ValidationUtils from '~/services/utils/validationUtils'
  4. export class TypeAssert implements AssertRule {
  5. supports(key: string): boolean {
  6. return key === 'type'
  7. }
  8. createRule(criteria: string): (value: unknown) => true | string {
  9. const validationUtils = new ValidationUtils()
  10. const { t } = useI18n()
  11. if (criteria === 'email') {
  12. return (email: unknown) =>
  13. (typeof email === 'string' && validationUtils.validEmail(email)) ||
  14. t('email_error')
  15. }
  16. if (criteria === 'url') {
  17. return (url: unknown) =>
  18. url === null ||
  19. (typeof url === 'string' && validationUtils.validUrl(url)) ||
  20. t('url_error')
  21. }
  22. if (criteria === 'integer') {
  23. return (value: unknown) =>
  24. Number.isInteger(value as number) || t('need_to_be_integer')
  25. }
  26. return () => true
  27. }
  28. }