2018-05-09 12:01:36 +05:30
|
|
|
import $ from 'jquery';
|
2018-03-17 18:26:18 +05:30
|
|
|
import GlFieldError from './gl_field_error';
|
2017-08-17 22:00:37 +05:30
|
|
|
|
|
|
|
const customValidationFlag = 'gl-field-error-ignore';
|
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
export default class GlFieldErrors {
|
2017-08-17 22:00:37 +05:30
|
|
|
constructor(form) {
|
|
|
|
this.form = $(form);
|
|
|
|
this.state = {
|
|
|
|
inputs: [],
|
2018-03-17 18:26:18 +05:30
|
|
|
valid: false,
|
2017-08-17 22:00:37 +05:30
|
|
|
};
|
|
|
|
this.initValidators();
|
|
|
|
}
|
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
initValidators() {
|
2017-08-17 22:00:37 +05:30
|
|
|
// register selectors here as needed
|
2019-05-18 00:54:41 +05:30
|
|
|
const validateSelectors = [':text', ':password', '[type=email]', '[type=url]', '[type=number]']
|
2018-12-13 13:39:08 +05:30
|
|
|
.map(selector => `input${selector}`)
|
|
|
|
.join(',');
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-12-13 13:39:08 +05:30
|
|
|
this.state.inputs = this.form
|
|
|
|
.find(validateSelectors)
|
|
|
|
.toArray()
|
2018-03-17 18:26:18 +05:30
|
|
|
.filter(input => !input.classList.contains(customValidationFlag))
|
|
|
|
.map(input => new GlFieldError({ input, formErrors: this }));
|
2017-08-17 22:00:37 +05:30
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
this.form.on('submit', GlFieldErrors.catchInvalidFormSubmit);
|
2017-08-17 22:00:37 +05:30
|
|
|
}
|
|
|
|
|
2018-12-13 13:39:08 +05:30
|
|
|
/* Necessary to prevent intercept and override invalid form submit
|
2017-08-17 22:00:37 +05:30
|
|
|
* because Safari & iOS quietly allow form submission when form is invalid
|
|
|
|
* and prevents disabling of invalid submit button by application.js */
|
|
|
|
|
2018-03-17 18:26:18 +05:30
|
|
|
static catchInvalidFormSubmit(e) {
|
|
|
|
const $form = $(e.currentTarget);
|
2017-09-10 17:25:29 +05:30
|
|
|
|
|
|
|
if (!$form.attr('novalidate')) {
|
2018-03-17 18:26:18 +05:30
|
|
|
if (!e.currentTarget.checkValidity()) {
|
|
|
|
e.preventDefault();
|
|
|
|
e.stopPropagation();
|
2017-09-10 17:25:29 +05:30
|
|
|
}
|
2017-08-17 22:00:37 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Public method for triggering validity updates manually */
|
|
|
|
updateFormValidityState() {
|
2018-12-13 13:39:08 +05:30
|
|
|
this.state.inputs.forEach(field => {
|
2017-08-17 22:00:37 +05:30
|
|
|
if (field.state.submitted) {
|
|
|
|
field.updateValidity();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-07-28 23:09:34 +05:30
|
|
|
get invalidInputs() {
|
|
|
|
return this.state.inputs.filter(
|
|
|
|
({
|
|
|
|
inputDomElement: {
|
|
|
|
validity: { valid },
|
|
|
|
},
|
|
|
|
}) => !valid,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
get focusedInvalidInput() {
|
|
|
|
return this.invalidInputs.find(({ inputElement }) => inputElement.is(':focus'));
|
|
|
|
}
|
|
|
|
|
|
|
|
focusInvalid() {
|
|
|
|
if (this.focusedInvalidInput) return;
|
|
|
|
|
|
|
|
this.invalidInputs[0].inputElement.focus();
|
2017-08-17 22:00:37 +05:30
|
|
|
}
|
|
|
|
}
|