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
|
|
|
|
2017-05-16 16:52:40 -04:00
|
|
|
import './gl_field_error';
|
2016-11-01 13:40:48 -04:00
|
|
|
|
2017-03-11 02:30:44 -05:00
|
|
|
const customValidationFlag = 'gl-field-error-ignore';
|
|
|
|
|
|
|
|
class GlFieldErrors {
|
|
|
|
constructor(form) {
|
|
|
|
this.form = $(form);
|
|
|
|
this.state = {
|
|
|
|
inputs: [],
|
|
|
|
valid: false
|
|
|
|
};
|
|
|
|
this.initValidators();
|
|
|
|
}
|
2016-09-09 08:21:00 -04:00
|
|
|
|
2017-03-11 02:30:44 -05:00
|
|
|
initValidators () {
|
|
|
|
// register selectors here as needed
|
|
|
|
const validateSelectors = [':text', ':password', '[type=email]']
|
|
|
|
.map((selector) => `input${selector}`).join(',');
|
2016-10-17 05:44:25 -04:00
|
|
|
|
2017-03-11 02:30:44 -05:00
|
|
|
this.state.inputs = this.form.find(validateSelectors).toArray()
|
|
|
|
.filter((input) => !input.classList.contains(customValidationFlag))
|
|
|
|
.map((input) => new window.gl.GlFieldError({ input, formErrors: this }));
|
2016-09-23 02:31:04 -04:00
|
|
|
|
2017-03-11 02:30:44 -05:00
|
|
|
this.form.on('submit', this.catchInvalidFormSubmit);
|
|
|
|
}
|
2016-09-09 08:21:00 -04:00
|
|
|
|
2017-03-11 02:30:44 -05: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 */
|
2016-09-23 02:31:04 -04:00
|
|
|
|
2017-03-11 02:30:44 -05:00
|
|
|
catchInvalidFormSubmit (event) {
|
2017-05-25 05:35:51 -04:00
|
|
|
const $form = $(event.currentTarget);
|
|
|
|
|
|
|
|
if (!$form.attr('novalidate')) {
|
|
|
|
if (!event.currentTarget.checkValidity()) {
|
|
|
|
event.preventDefault();
|
|
|
|
event.stopPropagation();
|
|
|
|
}
|
2016-09-09 08:21:00 -04:00
|
|
|
}
|
2017-03-11 02:30:44 -05:00
|
|
|
}
|
2016-09-09 08:21:00 -04:00
|
|
|
|
2017-05-07 18:35:56 -04:00
|
|
|
/* Public method for triggering validity updates manually */
|
|
|
|
updateFormValidityState() {
|
|
|
|
this.state.inputs.forEach((field) => {
|
|
|
|
if (field.state.submitted) {
|
|
|
|
field.updateValidity();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-03-11 02:30:44 -05:00
|
|
|
focusOnFirstInvalid () {
|
|
|
|
const firstInvalid = this.state.inputs.filter((input) => !input.inputDomElement.validity.valid)[0];
|
|
|
|
firstInvalid.inputElement.focus();
|
2016-09-09 08:21:00 -04:00
|
|
|
}
|
2017-03-11 02:30:44 -05:00
|
|
|
}
|
2016-09-09 08:21:00 -04:00
|
|
|
|
2017-03-11 02:30:44 -05:00
|
|
|
window.gl = window.gl || {};
|
|
|
|
window.gl.GlFieldErrors = GlFieldErrors;
|