import { Meta, Story, html } from '@open-wc/demoing-storybook';
/* eslint-disable import/no-extraneous-dependencies */
import { LionInput } from '@lion/input';
import '@lion/input-amount/lion-input-amount.js';
import '@lion/input-date/lion-input-date.js';
import '@lion/input-email/lion-input-email.js';
import '@lion/input/lion-input.js';
import {
DefaultSuccess,
EqualsLength,
IsDate,
IsEmail,
IsNumber,
loadDefaultFeedbackMessages,
MaxDate,
MaxLength,
MaxNumber,
MinDate,
MinLength,
MinMaxDate,
MinMaxLength,
MinMaxNumber,
MinNumber,
Required,
Validator,
Pattern,
} from '@lion/validate';
## Required Validator
The required validator can be put onto every form field element and will make sure that element is
not empty.
For an input that may mean that it is not an empty string,
while for a checkbox group it means at least one checkbox needs to be checked.
{() => {
loadDefaultFeedbackMessages();
return html`
`}}
```html
```
## String Validators
Useful on input elements it allows to define how many characters can be entered.
{html`
Rocks" is in this input #LionRocks'}
label="Pattern"
>
`}
```html
```
## Number Validators
Number validations assume that it's modelValue is actually a number.
Therefore it may only be used on input that have an appropriate parser/formatter like the input-amount.
{html`
`}
```html
```
## Date Validators
Date validators work with real javascript dates. Use them on input-date.
{() => {
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth();
const day = today.getDate();
const yesterday = new Date(year, month, day - 1);
const tomorrow = new Date(year, month, day + 1);
return html`
`;
}}
```js
const today = new Date();
const year = today.getFullYear();
const month = today.getMonth();
const day = today.getDate();
const yesterday = new Date(year, month, day - 1);
const tomorrow = new Date(year, month, day + 1);
```
```html
```
## Email Validator
{html`
`}
```html
```
## Validation Types
When defining your own component you can decide to allow for multiple types of validation.
By default only `error` is used, however there are certainly use cases where warning or success messages make sense.
{() => {
try {
class MyTypesInput extends LionInput {
static get validationTypes() {
return ['error', 'warning', 'info', 'success'];
}
}
customElements.define('my-types-input', MyTypesInput);
} catch (err) {
// expected as it is a demo
}
return html`
`;
}}
```js
try {
class MyTypesInput extends LionInput {
static get validationTypes() {
return ['error', 'warning', 'info', 'success'];
}
}
customElements.define('my-types-input', MyTypesInput);
} catch (err) {
// expected as it is a demo
}
```
```html
```
## Custom Validators
Here is an example how you can make your own validator and providing the error messages directly within.
You can even hard code localization in there if needed or you can use a localization system.
{() => {
class MyValidator extends Validator {
static get validatorName() {
return 'myValidator';
}
execute(modelValue, param) {
return modelValue !== param;
}
static getMessage({ fieldName, modelValue, params: param }) {
if (modelValue.length >= param.length - 1 && param.startsWith(modelValue)) {
return 'Almost there...';
}
return `No "${param}" found in ${fieldName}`;
}
}
return html`
`;
}
}
```js
class MyValidator extends Validator {
constructor(...args) {
super(...args);
}
static get validatorName() {
return 'myValidator';
}
execute(modelValue, param) {
return modelValue !== param;
}
static getMessage({ fieldName, modelValue, params: param }) {
if (modelValue.length >= param.length - 1 && param.startsWith(modelValue)) {
return 'Almost there...';
}
return `No "${param}" found in ${fieldName}`;
}
}
```
```html
```
## Default messages
To get default validation messages you need to import and call the `loadDefaultFeedbackMessages` function once in your application.
Sometimes the default messages don't make sense for your input field. In that case you want to override it by adding a `getMessage` function to your validator.
{html`
`}
```html
```
## Override fieldName
In the scenario that the default messages are correct, but you only want to change the `fieldName`, this can both be done for a single specific validator or for all at once.
{html`
`}
```html
```
## Asynchronous validation
{() => {
function pause(ms = 0) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, ms);
});
}
class AsyncValidator extends Validator {
constructor(...args) {
super(...args);
}
static get validatorName() {
return 'asyncValidator';
}
static get async() {
return true;
}
async execute() {
console.log('async pending...');
await pause(2000);
console.log('async done...');
return true;
}
static getMessage({ modelValue }) {
return `validated for modelValue: ${modelValue}...`;
}
}
return html`
`}}
```js
function pause(ms = 0) {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, ms);
});
}
class AsyncValidator extends Validator {
constructor(...args) {
super(...args);
}
static get validatorName() {
return 'asyncValidator';
}
static get async() {
return true;
}
async execute() {
console.log('async pending...');
await pause(2000);
console.log('async done...');
return true;
}
static getMessage({ modelValue }) {
return `validated for modelValue: ${modelValue}...`;
}
}
```
## Dynamic parameter change
{() => {
const beginDate = new Date('09/09/1990');
const minDateValidatorRef = new MinDate(beginDate, {
message: 'Fill in a date after your birth date',
});
return html`
{
if (!errorState) {
// Since graduation date is usually not before birth date
minDateValidatorRef.param = modelValue;
}
}}"
>
`}}
```js
const beginDate = new Date('09/09/1990');
const minDateValidatorRef = new MinDate(beginDate, {
message: 'Fill in a date after your birth date',
});
```
```html
{
if (!errorState) {
// Since graduation date is usually not before birth date
minDateValidatorRef.param = modelValue;
}
}}"
>
```
## Disabled inputs validation
According to the W3C specs, Disabled fields should not be validated.
Therefor if the attribute disabled is present on a lion-input it will not be validated.
{html`
`}
```html
```