2017-01-10 23:02:20 +00:00
|
|
|
/* eslint-disable comma-dangle, class-methods-use-this, max-len, space-before-function-paren, arrow-parens, no-param-reassign */
|
2016-11-01 17:40:48 +00:00
|
|
|
|
2016-11-03 21:38:54 +00:00
|
|
|
require('./gl_field_error');
|
2016-11-01 17:40:48 +00:00
|
|
|
|
2017-03-11 07:30:44 +00:00
|
|
|
const customValidationFlag = 'gl-field-error-ignore';
|
|
|
|
|
|
|
|
class GlFieldErrors {
|
|
|
|
constructor(form) {
|
|
|
|
this.form = $(form);
|
|
|
|
this.state = {
|
|
|
|
inputs: [],
|
|
|
|
valid: false
|
|
|
|
};
|
|
|
|
this.initValidators();
|
|
|
|
}
|
2016-09-09 12:21:00 +00:00
|
|
|
|
2017-03-11 07:30:44 +00:00
|
|
|
initValidators () {
|
|
|
|
// register selectors here as needed
|
|
|
|
const validateSelectors = [':text', ':password', '[type=email]']
|
|
|
|
.map((selector) => `input${selector}`).join(',');
|
2016-10-17 09:44:25 +00:00
|
|
|
|
2017-03-11 07:30:44 +00: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 06:31:04 +00:00
|
|
|
|
2017-03-11 07:30:44 +00:00
|
|
|
this.form.on('submit', this.catchInvalidFormSubmit);
|
|
|
|
}
|
2016-09-09 12:21:00 +00:00
|
|
|
|
2017-03-11 07:30:44 +00: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 06:31:04 +00:00
|
|
|
|
2017-03-11 07:30:44 +00:00
|
|
|
catchInvalidFormSubmit (event) {
|
|
|
|
if (!event.currentTarget.checkValidity()) {
|
|
|
|
event.preventDefault();
|
|
|
|
event.stopPropagation();
|
2016-09-09 12:21:00 +00:00
|
|
|
}
|
2017-03-11 07:30:44 +00:00
|
|
|
}
|
2016-09-09 12:21:00 +00:00
|
|
|
|
2017-03-11 07:30:44 +00:00
|
|
|
focusOnFirstInvalid () {
|
|
|
|
const firstInvalid = this.state.inputs.filter((input) => !input.inputDomElement.validity.valid)[0];
|
|
|
|
firstInvalid.inputElement.focus();
|
2016-09-09 12:21:00 +00:00
|
|
|
}
|
2017-03-11 07:30:44 +00:00
|
|
|
}
|
2016-09-09 12:21:00 +00:00
|
|
|
|
2017-03-11 07:30:44 +00:00
|
|
|
window.gl = window.gl || {};
|
|
|
|
window.gl.GlFieldErrors = GlFieldErrors;
|