Skip to content

Commit

Permalink
Add external validator to TextInput
Browse files Browse the repository at this point in the history
  • Loading branch information
SweetDealer committed Apr 26, 2024
1 parent 9d2a816 commit 5ca9dd1
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/InputValidator.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default class InputValidator {
}

/**
* @param {EditText} inputEl
* @param {EditText|TextInput} inputEl
* @param {*} valueToValidate
* @return {ValidationResult}
*/
Expand Down
24 changes: 22 additions & 2 deletions src/TextInput/TextInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export default class TextInput extends HTMLElement {
};
/** @type {string} */
#lastChangedValue;
// @ts-ignore
/** @type {InputValidator} */
#externalValidators = [];

connectedCallback() {
this.innerHTML = this.#htmlTemplate();
Expand All @@ -42,6 +45,12 @@ export default class TextInput extends HTMLElement {
window.removeEventListener("visibilitychange", this.#onVisibilityChange.bind(this), { capture: true });
}

// @ts-ignore
/** @param {InputValidator} validator */
addExternalValidator(validator) {
this.#externalValidators.push(validator);
}

/**
* Returns trimmed value of the input.
* @returns {string}
Expand All @@ -66,9 +75,20 @@ export default class TextInput extends HTMLElement {
}

checkValidity() {
const isValid = this.#validityState.checkValidity();
if (!this.#validityState.checkValidity()){
this.errorMessage = this.#validityState.errorMessage;
return false;
}
this.errorMessage = this.#validityState.errorMessage;
return isValid;
for (const /**@type {InputValidator} */ validator of this.#externalValidators) {
const result = validator.validate(this, this.value);
if (!result.isValid) {
this.errorMessage = result.errorMessage;
this.focus()
return false;
}
}
return true;
}

get errorMessage() {
Expand Down

0 comments on commit 5ca9dd1

Please sign in to comment.