debian-mirror-gitlab/app/assets/javascripts/gl_field_errors.js

57 lines
1.6 KiB
JavaScript
Raw Normal View History

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
const validateSelectors = [':text', ':password', '[type=email]']
2018-03-17 18:26:18 +05:30
.map(selector => `input${selector}`).join(',');
2017-08-17 22:00:37 +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
}
/* 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 */
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() {
this.state.inputs.forEach((field) => {
if (field.state.submitted) {
field.updateValidity();
}
});
}
2018-03-17 18:26:18 +05:30
focusOnFirstInvalid() {
const firstInvalid = this.state.inputs
.filter(input => !input.inputDomElement.validity.valid)[0];
2017-08-17 22:00:37 +05:30
firstInvalid.inputElement.focus();
}
}