Marin171

Form Validation

Jun 14th, 2023
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. function validate () {
  2. const html = {
  3. companyCheck: document.getElementById(`company`),
  4. submit: document.getElementById(`submit`),
  5. validDiv: document.getElementById(`valid`),
  6. companyInfo: document.getElementById(`companyInfo`)
  7. }
  8.  
  9. const inputFields = {
  10. username: document.getElementById(`username`),
  11. email: document.getElementById(`email`),
  12. password: document.getElementById(`password`),
  13. 'confirm-password': document.getElementById(`confirm-password`),
  14. companyNumber: document.getElementById(`companyNumber`),
  15.  
  16. }
  17.  
  18. const checkLength = (v, s, e) => v.length >= s && v.length <= e
  19. const checkPassword = (v, s, e, f) =>
  20. checkLength(v, s, e) && /^\w+$/g.test(v) && v === inputFields[f].value
  21.  
  22. const validate = {
  23. username: (v) => checkLength(v, 3, 20) && /^[a-zA-Z0-9]*$/g.test(v),
  24. password: (v) => checkPassword(v, 5, 15, 'confirm-password'),
  25. 'confirm-password': (v) => checkPassword(v, 5, 15, 'password'),
  26. email: (v) => /^.*@.*\..*$/g.test(v),
  27. companyNumber: (v, c) => c ? v >= 1000 && v <= 9999 : true
  28. }
  29.  
  30. const changeBorder = (c, e) => {
  31. const style = c ? 'border: none' : 'border-color: red'
  32.  
  33. e.style = style
  34. }
  35.  
  36. html.companyCheck.addEventListener('change', (e) => {
  37. if (e.target.checked === true) {
  38. html.companyInfo.style.display = 'block'
  39. } else {
  40. html.companyInfo.style.display = 'none'
  41. }
  42. })
  43.  
  44. html.submit.addEventListener('click', (e) => {
  45. e.preventDefault()
  46. const checked = html.companyCheck.checked
  47. let oneInvalid = false
  48.  
  49. Object.entries(inputFields).forEach(([name, valueField]) => {
  50. const valid = validate[name](valueField.value, checked)
  51.  
  52. changeBorder(valid, inputFields[name])
  53.  
  54. if (! valid) oneInvalid = true
  55. })
  56.  
  57. if (oneInvalid) {
  58. html.validDiv.style.display = 'none'
  59. } else {
  60. html.validDiv.style.display = 'block'
  61. }
  62. })
  63. }
Add Comment
Please, Sign In to add comment