From 5cc64991b13ae073b57f8089d8ad4adbfd0342f5 Mon Sep 17 00:00:00 2001 From: Konstantinos Norgias Date: Tue, 5 Apr 2022 12:53:46 +0200 Subject: [PATCH] chore: add eg for validator class that returns enum --- docs/fundamentals/systems/form/validate.md | 36 +++++++++++++++++++- packages/form-core/src/validate/Validator.js | 4 +-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/docs/fundamentals/systems/form/validate.md b/docs/fundamentals/systems/form/validate.md index 50409c144..ae2f3820d 100644 --- a/docs/fundamentals/systems/form/validate.md +++ b/docs/fundamentals/systems/form/validate.md @@ -110,7 +110,7 @@ As you can see the 'validators' property expects a map (an array of arrays). So, ### Validator classes -All validators extend from the default `Validator` class. Below example is an example of a validator could look like: +All validators extend from the default `Validator` class. Below is an example of what a validator could look like: ```js class EqualsText extends Validator { @@ -130,6 +130,40 @@ class EqualsText extends Validator { } ``` +The `execute()` method returns a boolean by default, but it can also be customized to return enums instead. In this example below, we customize the method to return one among some possible enums as strings. + +```js +class EnumOutComeValidator extends Validator { + static validatorName = 'EnumOutCome'; + + /** + * @param {string} modelValue + * @param {number} maxLength + * @returns {false|'overload'|'error'} + */ + execute(modelValue, maxLength) { + if (modelValue.length > maxLength) { + return 'overload'; + } else if (modelValue.length < 0) { + return 'error'; + } + return false; + } + + /** + * @param {{outcome: 'overload'|'error'|false}} opts + */ + static async getMessage({ outcome }) { + const results = { + overload: 'Too many characters!', + error: 'Something went wrong..', + false: 'All good!', + }; + return results[outcome]; + } +} +``` + ```html ``` diff --git a/packages/form-core/src/validate/Validator.js b/packages/form-core/src/validate/Validator.js index f4ec60243..0baa9d15c 100644 --- a/packages/form-core/src/validate/Validator.js +++ b/packages/form-core/src/validate/Validator.js @@ -50,9 +50,9 @@ export class Validator extends EventTarget { static async = false; /** - * The function that returns a validity outcome. When we need to shpw feedback, + * The function that returns a validity outcome. When we need to show feedback, * it should return true, otherwise false. So when an error\info|warning|success message - * needs to be shown, return true. For async Validators, the function canretun a Promise. + * needs to be shown, return true. For async Validators, the function can return a Promise. * It's also possible to return an enum. Let's say that a phone number can have multiple * states: 'invalid-country-code' | 'too-long' | 'too-short' * Those states can be retrieved in the getMessage