BigW Consortium Gitlab

gl_field_errors.js.es6 1.42 KB
Newer Older
1
/* eslint-disable */
2 3 4

//= require gl_field_error

5
((global) => {
6
  const customValidationFlag = 'gl-field-error-ignore';
7

8 9 10
  class GlFieldErrors {
    constructor(form) {
      this.form = $(form);
11 12 13 14
      this.state = {
        inputs: [],
        valid: false
      };
15 16
      this.initValidators();
    }
17

18
    initValidators () {
19 20 21 22 23
      // register selectors here as needed
      const validateSelectors = [':text', ':password', '[type=email]']
        .map((selector) => `input${selector}`).join(',');

      this.state.inputs = this.form.find(validateSelectors).toArray()
24
        .filter((input) => !input.classList.contains(customValidationFlag))
25
        .map((input) => new global.GlFieldError({ input, formErrors: this }));
26 27 28

      this.form.on('submit', this.catchInvalidFormSubmit);
    }
29

30 31 32 33 34 35 36 37
    /* Neccessary to prevent intercept and override invalid form submit
     * because Safari & iOS quietly allow form submission when form is invalid
     * and prevents disabling of invalid submit button by application.js */

    catchInvalidFormSubmit (event) {
      if (!event.currentTarget.checkValidity()) {
        event.preventDefault();
        event.stopPropagation();
38 39 40 41
      }
    }

    focusOnFirstInvalid () {
42 43
      const firstInvalid = this.state.inputs.filter((input) => !input.inputDomElement.validity.valid)[0];
      firstInvalid.inputElement.focus();
44 45 46 47 48 49
    }
  }

  global.GlFieldErrors = GlFieldErrors;

})(window.gl || (window.gl = {}));