validators.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. https://stackoverflow.com/a/46181/4468021
  3. */
  4. export const isEmail = (email: string): boolean => {
  5. if (!email) {
  6. return false;
  7. }
  8. const re =
  9. /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  10. return re.test(email);
  11. };
  12. // Allows splitting emails by comma, semicolon or newline
  13. export const emailSeparator = /[,;\n]/;
  14. /**
  15. * Validate multiple emails, stored as a separated string. Also validates that
  16. * emails are present
  17. */
  18. export const validateMultipleEmails = (emails: string, separator = emailSeparator) => {
  19. // Empty email is considered valid in this case
  20. if (!emails) {
  21. return true;
  22. }
  23. return emails
  24. .split(separator)
  25. .filter(Boolean)
  26. .every((email) => isEmail(email));
  27. };
  28. /**
  29. * Validate if image URL ends with allowed extension
  30. * @param fileName
  31. * @param allowedExtensions
  32. */
  33. export const isValidImageExt = (fileName = '', allowedExtensions = ['png', 'jpg', 'gif']) => {
  34. if (!fileName) {
  35. return true;
  36. }
  37. const parts = fileName.split('.');
  38. return allowedExtensions.includes(parts[parts.length - 1]);
  39. };