input-validator.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. export default function inputValidator(options) {
  2. const { selector } = options
  3. const inputEl = document.querySelector(selector)
  4. inputEl.addEventListener('input', markDirty)
  5. inputEl.addEventListener('change', markDirty)
  6. inputEl.addEventListener('blur', insertInvalidMessage)
  7. // Mark an input as "dirty": the user has typed something in at some point
  8. function markDirty() {
  9. // Note: this is used for the input styling as well as checks when inserting invalid
  10. // message below
  11. inputEl.dataset.olDirty = true
  12. }
  13. function insertInvalidMessage() {
  14. if (!inputEl.validity.valid) {
  15. // Already have a invalid message, don't insert another
  16. if (inputEl._invalid_message_el) return
  17. // Only show the message if the input is "dirty"
  18. if (!inputEl.dataset.olDirty) return
  19. const messageEl = createMessageEl({
  20. message: getMessage(inputEl),
  21. ...options,
  22. })
  23. inputEl.insertAdjacentElement('afterend', messageEl)
  24. // Add a reference so we can remove the element when the input becomes valid
  25. inputEl._invalid_message_el = messageEl
  26. } else {
  27. if (!inputEl._invalid_message_el) return
  28. // Remove the message element
  29. inputEl._invalid_message_el.remove()
  30. // Clean up the reference
  31. delete inputEl._invalid_message_el
  32. }
  33. }
  34. function cleanUp() {
  35. inputEl.removeEventListener('input change', markDirty)
  36. inputEl.removeEventListener('blue', insertInvalidMessage)
  37. delete inputEl._invalid_message_el
  38. delete inputEl.dataset.olDirty
  39. }
  40. return cleanUp
  41. }
  42. function createMessageEl({ message, messageClasses = [] }) {
  43. const el = document.createElement('span')
  44. // From what I understand, using textContent means that we're safe from XSS
  45. el.textContent = message
  46. el.classList.add(...messageClasses)
  47. return el
  48. }
  49. function getMessage(el) {
  50. // Could be extended to all ValidityState properties: https://developer.mozilla.org/en-US/docs/Web/API/ValidityState
  51. const { valueMissing, typeMismatch } = el.validity
  52. if (valueMissing) {
  53. return el.dataset.olInvalidValueMissing || 'Missing required value'
  54. } else if (typeMismatch) {
  55. return el.dataset.olInvalidTypeMismatch || 'Invalid type' // FIXME: Bad default
  56. } else {
  57. return 'Invalid'
  58. }
  59. }