diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2023-02-21 03:08:01 +0300 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2023-02-21 03:08:01 +0300 |
commit | 5e396cd53ef1686fbc02b446a6a44d8a69ce8755 (patch) | |
tree | 81f60b948fa91d230b3494a549c81a1a2e8b7d7e /app/assets/javascripts/validators | |
parent | 61a1cd3b8389a7f5553bae90655710ed9b39ddff (diff) |
Add latest changes from gitlab-org/gitlab@master
Diffstat (limited to 'app/assets/javascripts/validators')
-rw-r--r-- | app/assets/javascripts/validators/length_validator.js | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/app/assets/javascripts/validators/length_validator.js b/app/assets/javascripts/validators/length_validator.js new file mode 100644 index 00000000000..6ce453fe40b --- /dev/null +++ b/app/assets/javascripts/validators/length_validator.js @@ -0,0 +1,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(); + } +} |