blob: eec7a138ea74e09bc0f18f3fe0056f4c1c8d5b3b (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
import $ from 'jquery';
import GlFieldError from './gl_field_error';
const customValidationFlag = 'gl-field-error-ignore';
export default class GlFieldErrors {
constructor(form) {
this.form = $(form);
this.state = {
inputs: [],
valid: false,
};
this.initValidators();
}
initValidators() {
// register selectors here as needed
const validateSelectors = [':text', ':password', '[type=email]', '[type=url]', '[type=number]']
.map((selector) => `input${selector}`)
.join(',');
this.state.inputs = this.form
.find(validateSelectors)
.toArray()
.filter((input) => !input.classList.contains(customValidationFlag))
.map((input) => new GlFieldError({ input, formErrors: this }));
this.form.on('submit', GlFieldErrors.catchInvalidFormSubmit);
}
/* Necessary 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 */
static catchInvalidFormSubmit(e) {
const $form = $(e.currentTarget);
if (!$form.attr('novalidate')) {
if (!e.currentTarget.checkValidity()) {
e.preventDefault();
e.stopPropagation();
}
}
}
/* Public method for triggering validity updates manually */
updateFormValidityState() {
this.state.inputs.forEach((field) => {
if (field.state.submitted) {
field.updateValidity();
}
});
}
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();
}
}
|