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
|
import InputValidator from '~/validators/input_validator';
const errorMessageClass = 'gl-field-error';
export const isAboveMaxLength = (str, maxLength) => {
return str.length > parseInt(maxLength, 10);
};
export const isBelowMinLength = (value, minLength, allowEmpty) => {
const isValueNotAllowedOrNotEmpty = allowEmpty !== 'true' || value.length !== 0;
const isValueBelowMinLength = value.length < parseInt(minLength, 10);
return isValueBelowMinLength && isValueNotAllowedOrNotEmpty;
};
export default class LengthValidator extends InputValidator {
constructor(opts = {}) {
super();
const container = opts.container || '';
const validateLengthElements = document.querySelectorAll(`${container} .js-validate-length`);
validateLengthElements.forEach((element) =>
element.addEventListener('input', this.eventHandler.bind(this)),
);
}
eventHandler(event) {
this.inputDomElement = event.target;
this.inputErrorMessage = this.inputDomElement.parentElement.querySelector(
`.${errorMessageClass}`,
);
const { value } = this.inputDomElement;
const {
minLength,
minLengthMessage,
maxLengthMessage,
maxLength,
allowEmpty,
} = this.inputDomElement.dataset;
this.invalidInput = false;
if (isAboveMaxLength(value, maxLength)) {
this.invalidInput = true;
this.errorMessage = maxLengthMessage;
}
if (isBelowMinLength(value, minLength, allowEmpty)) {
this.invalidInput = true;
this.errorMessage = minLengthMessage;
}
this.setValidationStateAndMessage();
}
}
|