2017-01-10 18:02:20 -05:00
|
|
|
/* eslint-disable comma-dangle, class-methods-use-this, max-len, space-before-function-paren, arrow-parens, no-param-reassign */
|
2016-11-01 13:40:48 -04:00
|
|
|
|
|
|
|
//= require gl_field_error
|
|
|
|
|
2016-09-09 08:21:00 -04:00
|
|
|
((global) => {
|
2016-10-21 07:49:09 -04:00
|
|
|
const customValidationFlag = 'gl-field-error-ignore';
|
2016-09-23 04:29:21 -04:00
|
|
|
|
2016-09-23 02:31:04 -04:00
|
|
|
class GlFieldErrors {
|
|
|
|
constructor(form) {
|
|
|
|
this.form = $(form);
|
2016-09-23 04:29:21 -04:00
|
|
|
this.state = {
|
|
|
|
inputs: [],
|
|
|
|
valid: false
|
|
|
|
};
|
2016-09-23 02:31:04 -04:00
|
|
|
this.initValidators();
|
|
|
|
}
|
2016-09-09 08:21:00 -04:00
|
|
|
|
2016-09-23 02:31:04 -04:00
|
|
|
initValidators () {
|
2016-10-17 05:44:25 -04:00
|
|
|
// register selectors here as needed
|
|
|
|
const validateSelectors = [':text', ':password', '[type=email]']
|
|
|
|
.map((selector) => `input${selector}`).join(',');
|
|
|
|
|
|
|
|
this.state.inputs = this.form.find(validateSelectors).toArray()
|
2016-09-23 04:29:21 -04:00
|
|
|
.filter((input) => !input.classList.contains(customValidationFlag))
|
2016-10-27 09:49:07 -04:00
|
|
|
.map((input) => new global.GlFieldError({ input, formErrors: this }));
|
2016-09-23 02:31:04 -04:00
|
|
|
|
|
|
|
this.form.on('submit', this.catchInvalidFormSubmit);
|
|
|
|
}
|
2016-09-09 08:21:00 -04:00
|
|
|
|
2016-09-23 02:31:04 -04:00
|
|
|
/* 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();
|
2016-09-09 08:21:00 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
focusOnFirstInvalid () {
|
2016-09-28 06:59:58 -04:00
|
|
|
const firstInvalid = this.state.inputs.filter((input) => !input.inputDomElement.validity.valid)[0];
|
|
|
|
firstInvalid.inputElement.focus();
|
2016-09-09 08:21:00 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
global.GlFieldErrors = GlFieldErrors;
|
|
|
|
})(window.gl || (window.gl = {}));
|