SFRA Server-side Javascript - Source: components/clientSideValidation.js menu

SFRA / Client-side JS / Source: components/clientSideValidation.js

  1. 'use strict';
  2. /**
  3. * Validate whole form. Requires `this` to be set to form object
  4. * @param {jQuery.event} event - Event to be canceled if form is invalid.
  5. * @returns {boolean} - Flag to indicate if form is valid
  6. */
  7. function validateForm(event) {
  8. var valid = true;
  9. if (this.checkValidity && !this.checkValidity()) {
  10. // safari
  11. valid = false;
  12. if (event) {
  13. event.preventDefault();
  14. event.stopPropagation();
  15. event.stopImmediatePropagation();
  16. }
  17. $(this).find('input, select').each(function () {
  18. if (!this.validity.valid) {
  19. $(this).trigger('invalid', this.validity);
  20. }
  21. });
  22. }
  23. return valid;
  24. }
  25. /**
  26. * Remove all validation. Should be called every time before revalidating form
  27. * @param {element} form - Form to be cleared
  28. * @returns {void}
  29. */
  30. function clearForm(form) {
  31. $(form).find('.form-control.is-invalid').removeClass('is-invalid');
  32. }
  33. module.exports = {
  34. invalid: function () {
  35. $('form input, form select').on('invalid', function (e) {
  36. e.preventDefault();
  37. this.setCustomValidity('');
  38. if (!this.validity.valid) {
  39. var validationMessage = this.validationMessage;
  40. $(this).addClass('is-invalid');
  41. if (this.validity.patternMismatch && $(this).data('pattern-mismatch')) {
  42. validationMessage = $(this).data('pattern-mismatch');
  43. }
  44. if ((this.validity.rangeOverflow || this.validity.rangeUnderflow)
  45. && $(this).data('range-error')) {
  46. validationMessage = $(this).data('range-error');
  47. }
  48. if ((this.validity.tooLong || this.validity.tooShort)
  49. && $(this).data('range-error')) {
  50. validationMessage = $(this).data('range-error');
  51. }
  52. if (this.validity.valueMissing && $(this).data('missing-error')) {
  53. validationMessage = $(this).data('missing-error');
  54. }
  55. $(this).parents('.form-group').find('.invalid-feedback')
  56. .text(validationMessage);
  57. }
  58. });
  59. },
  60. submit: function () {
  61. $('form').on('submit', function (e) {
  62. return validateForm.call(this, e);
  63. });
  64. },
  65. buttonClick: function () {
  66. $('form button[type="submit"], form input[type="submit"]').on('click', function () {
  67. // clear all errors when trying to submit the form
  68. clearForm($(this).parents('form'));
  69. });
  70. },
  71. functions: {
  72. validateForm: function (form, event) {
  73. validateForm.call($(form), event || null);
  74. },
  75. clearForm: clearForm
  76. }
  77. };