Guest User

Untitled

a guest
Feb 20th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. //npm install --save validate.js
  2. import validate from 'validate.js';
  3. import {ERROR} from './constants.js';
  4.  
  5. const constraints = {
  6. email: {
  7. presence: true,
  8. email: true
  9. },
  10. password: {
  11. presence: true,
  12. length: {
  13. minimum: 6
  14. },
  15. format: {
  16. //at least one uppercase letter, one lowercase letter and one number
  17. pattern: '^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).+$'
  18. }
  19. },
  20. select: {
  21. presence: true
  22. },
  23.  
  24. username: {
  25. presence: true,
  26. length: {
  27. minimum: 1,
  28. maximum: 20
  29. },
  30. format: {
  31. // We don't allow anything that a-z and 0-9
  32. pattern: '[a-z0-9]+',
  33. // but we don't care if the username is uppercase or lowercase
  34. flags: 'i',
  35. message: 'can only contain a-z and 0-9'
  36. }
  37. },
  38. 'password_confirm': {
  39. presence: true,
  40. // and it needs to be equal to the other password
  41. equality: {
  42. attribute: 'password',
  43. message: '^The passwords does not match'
  44. }
  45. }
  46.  
  47. };
  48.  
  49. const form = document.querySelectorAll('.js-form-valid');
  50.  
  51. for (let i = 0; i < form.length; i++) {
  52.  
  53. form[i].addEventListener('submit', function(e) {
  54. handleFormSubmit(form[i], e);
  55. });
  56.  
  57. let inputs = form[i].querySelectorAll('input, textarea, select');
  58.  
  59. for (let j = 0; j < inputs.length; ++j) {
  60. inputs[j].addEventListener('change', function() {
  61. let errors = validate(form[i], constraints) || {};
  62. handleChangeInput(this, errors[this.name]);
  63. });
  64. };
  65. };
  66.  
  67. function handleChangeInput(input, errors) {
  68. if (errors) {
  69. input.classList.add(ERROR);
  70. } else {
  71. input.classList.remove(ERROR);
  72. };
  73. };
  74.  
  75. function handleFormSubmit(form, e) {
  76. let errors = validate(form, constraints) || {};
  77. let keys = Object.keys(errors);
  78. for (let i = 0; i < keys.length; i++) {
  79. let inputs = form.querySelectorAll('input[name="'+keys[i]+'"], select[name="'+keys[i]+'"]');
  80. for (let j = 0; j < inputs.length; j++) {
  81. if (inputs[j].name === keys[i]) {
  82. e.preventDefault();
  83. inputs[j].classList.add(ERROR);
  84. };
  85. };
  86.  
  87. };
  88.  
  89. if (Object.keys(errors).length === 0) {
  90. showSuccess(e);
  91. };
  92. };
  93.  
  94. function showSuccess(e) {
  95. e.preventDefault();
  96. alert('success');
  97. };
Add Comment
Please, Sign In to add comment