var.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { MAX_VAR_KEY_LENGHT, VAR_ITEM_TEMPLATE, getMaxVarNameLength } from '@/config'
  2. const otherAllowedRegex = /^[a-zA-Z0-9_]+$/
  3. export const getNewVar = (key: string) => {
  4. return {
  5. ...VAR_ITEM_TEMPLATE,
  6. key,
  7. name: key.slice(0, getMaxVarNameLength(key)),
  8. }
  9. }
  10. const checkKey = (key: string, canBeEmpty?: boolean) => {
  11. if (key.length === 0 && !canBeEmpty)
  12. return 'canNoBeEmpty'
  13. if (canBeEmpty && key === '')
  14. return true
  15. if (key.length > MAX_VAR_KEY_LENGHT)
  16. return 'tooLong'
  17. if (otherAllowedRegex.test(key)) {
  18. if (/[0-9]/.test(key[0]))
  19. return 'notStartWithNumber'
  20. return true
  21. }
  22. return 'notValid'
  23. }
  24. export const checkKeys = (keys: string[], canBeEmpty?: boolean) => {
  25. let isValid = true
  26. let errorKey = ''
  27. let errorMessageKey = ''
  28. keys.forEach((key) => {
  29. if (!isValid)
  30. return
  31. const res = checkKey(key, canBeEmpty)
  32. if (res !== true) {
  33. isValid = false
  34. errorKey = key
  35. errorMessageKey = res
  36. }
  37. })
  38. return { isValid, errorKey, errorMessageKey }
  39. }