Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. const isFn = x => typeof x === 'function'
  2.  
  3. const plural = (words, count) => {
  4. words = words.split('|').map(x => x.trim())
  5. return count > 1 ? words[2].replace('{n}', count) : words[count]
  6. }
  7.  
  8. // Given a Vuelidate validations object, find the validator keys
  9. export function extractValidatorKeys (validations, validators = []) {
  10. const keys = Object.keys(validations)
  11. validators.push(...keys.filter(x => isFn(validations[x])))
  12. keys
  13. .filter(x => !isFn(validations[x]))
  14. .forEach(x => extractValidatorKeys(validations[x], validators))
  15. return validators
  16. }
  17.  
  18.  
  19. export const getValidationMessage = messages => validations => {
  20. let keys = extractValidatorKeys(validations)
  21. // check to make sure all validators have corresponding error messages
  22. const missing = keys.filter(x => !(x in messages))
  23. if (missing.length) {
  24. console.warn(`Validators missing validation messages: ${missing.join(', ')}`)
  25. keys = keys.filter(x => missing.indexOf(x) < 0)
  26. }
  27. const keyLen = keys.length
  28.  
  29. // Vue component method
  30. // Given a vuelidate field object, maybe return an error messsage
  31. return function (field) {
  32. if (!field.$dirty) return null
  33. let key
  34. for (let i = 0; i < keyLen; i++) {
  35. key = keys[i]
  36. if (field[key] === false) return messages[key](field.$params[key])
  37. }
  38. return null
  39. }
  40. }
  41.  
  42. export const validationMessages = {
  43. required: () => 'Required',
  44. email: () => 'Invalid email',
  45. txtMinLen: params => {
  46. const min = plural(
  47. 'no characters | one character | {n} characters',
  48. params.min
  49. )
  50. return `Must be at least ${min}`
  51. }
  52. }
  53.  
  54. // ***************************************************************
  55. // Usage Example
  56. // ***************************************************************
  57. // <template>
  58. // <div>
  59. // <input v-model="name" />
  60. // <span>{{errors($v.name)}}</span>
  61. // </div>
  62. // </template>
  63.  
  64. // <script>
  65. // import { required, minLength } from 'vuelidate/lib/validators'
  66.  
  67. // const validations = {
  68. // name: {
  69. // required,
  70. // txtMinLen: minLength(2)
  71. // }
  72. // }
  73. //
  74. // export default {
  75. // data () {
  76. // return { name: '' }
  77. // },
  78. // validations,
  79. // methods: {
  80. // errors: getValidationMessage(validationMessages)(validations)
  81. // }
  82. // }
  83. // </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement