debian-mirror-gitlab/app/assets/javascripts/validators/length_validator.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

57 lines
1.6 KiB
JavaScript
Raw Normal View History

2022-06-21 17:19:12 +05:30
import InputValidator from '~/validators/input_validator';
2019-09-04 21:01:54 +05:30
const errorMessageClass = 'gl-field-error';
2023-05-27 22:25:52 +05:30
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;
};
2019-09-04 21:01:54 +05:30
export default class LengthValidator extends InputValidator {
constructor(opts = {}) {
super();
const container = opts.container || '';
const validateLengthElements = document.querySelectorAll(`${container} .js-validate-length`);
2021-03-08 18:12:59 +05:30
validateLengthElements.forEach((element) =>
2019-09-04 21:01:54 +05:30
element.addEventListener('input', this.eventHandler.bind(this)),
);
}
eventHandler(event) {
this.inputDomElement = event.target;
this.inputErrorMessage = this.inputDomElement.parentElement.querySelector(
`.${errorMessageClass}`,
);
const { value } = this.inputDomElement;
2020-07-28 23:09:34 +05:30
const {
minLength,
minLengthMessage,
maxLengthMessage,
maxLength,
2023-05-27 22:25:52 +05:30
allowEmpty,
2020-07-28 23:09:34 +05:30
} = this.inputDomElement.dataset;
this.invalidInput = false;
2023-05-27 22:25:52 +05:30
if (isAboveMaxLength(value, maxLength)) {
2020-07-28 23:09:34 +05:30
this.invalidInput = true;
this.errorMessage = maxLengthMessage;
}
2023-05-27 22:25:52 +05:30
if (isBelowMinLength(value, minLength, allowEmpty)) {
2020-07-28 23:09:34 +05:30
this.invalidInput = true;
this.errorMessage = minLengthMessage;
}
2019-09-04 21:01:54 +05:30
this.setValidationStateAndMessage();
}
}