useInputRules.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { useI18n } from "vue-i18n";
  2. export const useInputRules = () => {
  3. const { t } = useI18n();
  4. // Regex patterns
  5. const emailPattern =
  6. /^(([^<>()[\]\\.,;:\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,}))$/;
  7. const cpfPattern = /^[0-9]{3}\.[0-9]{3}\.[0-9]{3}-[0-9]{2}$/;
  8. const cnpjPattern = /^[0-9]{2}\.[0-9]{3}\.[0-9]{3}\/[0-9]{4}-[0-9]{2}$/;
  9. const passwordPattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/;
  10. const cepPattern = /^[0-9]{5}-[0-9]{3}$/;
  11. const inputRules = {
  12. required: (value) => !!value || t("validation.rules.required"),
  13. requiredNumber: (value) => !isNaN(value) || t("validation.rules.required"),
  14. requiredHideMessage: (value) => !!value,
  15. min: (min) => (value) =>
  16. value?.length >= min ||
  17. `${t("validation.rules.min")} ${min} ${t("validation.rules.characters")}`,
  18. max: (max) => (value) =>
  19. value?.length <= max ||
  20. `${t("validation.rules.max")} ${max} ${t("validation.rules.characters")}`,
  21. minValue: (min) => (value) =>
  22. value >= min || `${t("validation.rules.min")} ${min}`,
  23. maxValue: (max) => (value) =>
  24. value <= max || `${t("validation.rules.max")} ${max}`,
  25. email: (value) =>
  26. !value || emailPattern.test(value) || t("validation.rules.email"),
  27. emails: (value) => {
  28. if (!value) return true;
  29. const emails = value.split(";").map((email) => email.trim());
  30. return (
  31. emails.every((email) => inputRules.email(email) === true) ||
  32. t("validation.rules.email")
  33. );
  34. },
  35. cpf: (value) =>
  36. !value || cpfPattern.test(value) || t("validation.rules.cpf"),
  37. cnpj: (value) =>
  38. !value || cnpjPattern.test(value) || t("validation.rules.cnpj"),
  39. samePassword: (otherValue) => (value) =>
  40. value === otherValue || t("validation.rules.same_password"),
  41. password: (value) =>
  42. !value || passwordPattern.test(value) || t("validation.rules.password"),
  43. cep: (value) => {
  44. return cepPattern.test(value) || t("validation.rules.cep");
  45. },
  46. };
  47. return {
  48. inputRules,
  49. };
  50. };