You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
3.2 KiB

3 years ago
  1. <field-error>
  2. <div class="field-error" if={ state.errors.length > 0 }>
  3. <ul>
  4. <li each={ error in state.errors }>
  5. { error }
  6. </li>
  7. </ul>
  8. </div>
  9. <script>
  10. /**
  11. * Shows errors of Validation and raise a element to
  12. * trigger single validation of field
  13. *
  14. * <field-error name="name" nofieldupdate></field-error>
  15. *
  16. * @author Björn Hase, Tentakelfabrik, me@tentakelfabrik.de
  17. *
  18. */
  19. export default {
  20. state: {
  21. errors: [
  22. ],
  23. },
  24. /**
  25. *
  26. *
  27. * @param {Object} props [description]
  28. * @param {Object} state [description]
  29. *
  30. */
  31. onMounted(props, state)
  32. {
  33. // getting parent element for entire field
  34. const parent = this.root.closest('.field-group')
  35. // getting current element by name
  36. const element = document.querySelector('[name="' + props.name + '"]')
  37. // getting form
  38. const form = element.closest('form')
  39. // element, form are exists and nofieldupdate is not set
  40. // each change of the element dispatch a event to form validation
  41. if (element && form && !props.nofieldupdate) {
  42. element.addEventListener('input', (event) => {
  43. this.dispatchCustomEvent(event, form, props.name)
  44. })
  45. }
  46. // add custom event to listen to form-validation
  47. this.root.addEventListener('form-validation', (event) => {
  48. this.onFormValidation(event, parent)
  49. })
  50. },
  51. /**
  52. * process form validation triggered by form
  53. *
  54. * @param {Event} event
  55. * @param {Element} parent
  56. *
  57. */
  58. onFormValidation(event, parent)
  59. {
  60. // if detail is a value, set to errors
  61. if (event.detail) {
  62. this.state.errors = event.detail
  63. parent.classList.add('field--error')
  64. parent.classList.remove('field--valid')
  65. } else {
  66. this.state.errors = []
  67. parent.classList.remove('field--error')
  68. parent.classList.add('field--valid')
  69. }
  70. this.update()
  71. },
  72. /**
  73. * create event to send to form validation
  74. *
  75. * @param {Event} event
  76. * @param {Element} form
  77. * @param {string} name
  78. *
  79. */
  80. dispatchCustomEvent(event, form, name)
  81. {
  82. const fieldUpdateEvent = new CustomEvent('field-update', {
  83. 'detail': {
  84. 'name': name,
  85. 'value': event.target.value
  86. }
  87. })
  88. form.dispatchEvent(fieldUpdateEvent)
  89. },
  90. }
  91. </script>
  92. </field-error>