Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add error messages to field validation examples #3685

Merged
merged 19 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions frontend/demo/component/combobox/combo-box-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export class Example extends LitElement {
allowed-char-pattern="[A-Z]"
label="Country code"
helper-text="2-letter uppercase ISO country code"
error-message="Field is required"
allow-custom-value
.items="${['DE', 'FI', 'US']}"
></vaadin-combo-box>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ function Example() {
allowedCharPattern="[A-Z]"
label="Country code"
helperText="2-letter uppercase ISO country code"
errorMessage="Field is required"
allowCustomValue
items={['DE', 'FI', 'US']}
/>
Expand Down
18 changes: 11 additions & 7 deletions frontend/demo/component/datepicker/date-picker-validation.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import 'Frontend/demo/init'; // hidden-source-line
import '@vaadin/date-picker';
import { addDays, formatISO, isAfter, isBefore } from 'date-fns';
import dateFnsParse from 'date-fns/parse';
import { addDays, formatISO } from 'date-fns';
import { html, LitElement } from 'lit';
import { customElement, state } from 'lit/decorators.js';
import type { DatePickerChangeEvent } from '@vaadin/date-picker';
import type { DatePicker, DatePickerValidatedEvent } from '@vaadin/date-picker';
import { applyTheme } from 'Frontend/generated/theme';

@customElement('date-picker-validation')
Expand All @@ -31,14 +30,19 @@ export class Example extends LitElement {
<vaadin-date-picker
label="Appointment date"
helper-text="Must be within 60 days from today"
required
.min="${formatISO(this.minDate, { representation: 'date' })}"
.max="${formatISO(this.maxDate, { representation: 'date' })}"
.errorMessage="${this.errorMessage}"
@change="${({ target }: DatePickerChangeEvent) => {
const date = dateFnsParse(target.value ?? '', 'yyyy-MM-dd', new Date());
if (isBefore(date, this.minDate)) {
@validated="${(event: DatePickerValidatedEvent) => {
const field = event.target as DatePicker;
Copy link
Contributor Author

@vursen vursen Sep 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've created a proposal to improve typing for event.target in CustomEvent-based component events: vaadin/web-components#7868

if (!field.value && (field.inputElement as HTMLInputElement).value) {
Copy link
Contributor Author

@vursen vursen Sep 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've created a proposal to make the type of inputElement more specific to eliminate the need for manual casting in listeners: vaadin/web-components#7879

this.errorMessage = 'Invalid date format';
} else if (!field.value) {
this.errorMessage = 'Field is required';
} else if (field.value < field.min!) {
Copy link
Contributor Author

@vursen vursen Sep 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ISO format is lexicographically ordered, so we can use JS comparison operators to compare date strings directly. This simplifies the solution a bit.

this.errorMessage = 'Too early, choose another date';
} else if (isAfter(date, this.maxDate)) {
} else if (field.value > field.max!) {
this.errorMessage = 'Too late, choose another date';
} else {
this.errorMessage = '';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { reactExample } from 'Frontend/demo/react-example'; // hidden-source-line
import React from 'react'; // hidden-source-line
import { useSignals } from '@preact/signals-react/runtime'; // hidden-source-line
import { addDays, formatISO, isAfter, isBefore, parse } from 'date-fns';
import { addDays, formatISO } from 'date-fns';
import { useComputed, useSignal } from '@vaadin/hilla-react-signals';
import { DatePicker } from '@vaadin/react-components/DatePicker.js';
import { DatePicker, type DatePickerElement } from '@vaadin/react-components/DatePicker.js';

function Example() {
useSignals(); // hidden-source-line
Expand All @@ -16,14 +16,19 @@ function Example() {
<DatePicker
label="Appointment date"
helperText="Must be within 60 days from today"
required
min={formatISO(minDate.value, { representation: 'date' })}
max={formatISO(maxDate.value, { representation: 'date' })}
errorMessage={errorMessage.value}
onChange={({ target }) => {
const date = parse(target.value ?? '', 'yyyy-MM-dd', new Date());
if (isBefore(date, minDate.value)) {
onValidated={(event) => {
const field = event.target as DatePickerElement;
if (!field.value && (field.inputElement as HTMLInputElement).value) {
errorMessage.value = 'Invalid date format';
} else if (!field.value) {
errorMessage.value = 'Field is required';
Comment on lines +25 to +28
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we could simplify this a bit to only check !field.value once:

Suggested change
if (!field.value && (field.inputElement as HTMLInputElement).value) {
errorMessage.value = 'Invalid date format';
} else if (!field.value) {
errorMessage.value = 'Field is required';
if (!field.value) {
const notEmpty = (field.inputElement as HTMLInputElement).value;
errorMessage.value = notEmpty ? 'Invalid date format' : 'Field is required';

Copy link
Contributor Author

@vursen vursen Oct 1, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO, the current approach has a benefit that it keeps all error messages at the same indentation level, which makes them a bit easier to scan.

} else if (field.value < field.min!) {
errorMessage.value = 'Too early, choose another date';
} else if (isAfter(date, maxDate.value)) {
} else if (field.value > field.max!) {
errorMessage.value = 'Too late, choose another date';
} else {
errorMessage.value = '';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
import 'Frontend/demo/init'; // hidden-source-line
import '@vaadin/date-time-picker';
import { addDays, format, isAfter, isBefore, parseISO } from 'date-fns';
import { addDays, format } from 'date-fns';
import { html, LitElement } from 'lit';
import { customElement, state } from 'lit/decorators.js';
import type { DateTimePickerChangeEvent } from '@vaadin/date-time-picker';
import type { DatePicker } from '@vaadin/date-picker';
import type { DateTimePicker, DateTimePickerValidatedEvent } from '@vaadin/date-time-picker';
import type { TimePicker } from '@vaadin/time-picker';
import { applyTheme } from 'Frontend/generated/theme';

const dateTimeFormat = `yyyy-MM-dd'T'HH:00:00`;

@customElement('date-time-picker-validation')
export class Example extends LitElement {
@state()
private errorMessage = '';

@state()
private initialValue = addDays(new Date(), 7);

@state()
private minDate = new Date();

Expand All @@ -33,17 +30,28 @@ export class Example extends LitElement {
return html`
<!-- tag::snippet[] -->
<vaadin-date-time-picker
required
label="Appointment date and time"
helper-text="Must be within 60 days from today"
.value="${format(this.initialValue, dateTimeFormat)}"
.min="${format(this.minDate, dateTimeFormat)}"
.max="${format(this.maxDate, dateTimeFormat)}"
.min="${format(this.minDate, `yyyy-MM-dd'T'HH:00:00`)}"
.max="${format(this.maxDate, `yyyy-MM-dd'T'HH:00:00`)}"
.errorMessage="${this.errorMessage}"
@change="${({ target }: DateTimePickerChangeEvent) => {
const date = parseISO(target.value ?? '');
if (isBefore(date, this.minDate)) {
@validated="${(event: DateTimePickerValidatedEvent) => {
const field = event.target as DateTimePicker;
const datePicker: DatePicker = field.querySelector('[slot=date-picker]')!;
const timePicker: TimePicker = field.querySelector('[slot=time-picker]')!;
const hasBadDateInput =
!datePicker.value && !!(datePicker.inputElement as HTMLInputElement).value;
const hasBadTimeInput =
!timePicker.value && !!(timePicker.inputElement as HTMLInputElement).value;

if (hasBadDateInput || hasBadTimeInput) {
this.errorMessage = 'Invalid date or time';
} else if (!field.value) {
this.errorMessage = 'Field is required';
} else if (field.value < field.min!) {
this.errorMessage = 'Too early, choose another date and time';
} else if (isAfter(date, this.maxDate)) {
} else if (field.value > field.max!) {
this.errorMessage = 'Too late, choose another date and time';
} else {
this.errorMessage = '';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,32 +1,45 @@
import { reactExample } from 'Frontend/demo/react-example'; // hidden-source-line
import React from 'react'; // hidden-source-line
import { useSignals } from '@preact/signals-react/runtime'; // hidden-source-line
import { addDays, format, isAfter, isBefore, parseISO } from 'date-fns';
import { addDays, format } from 'date-fns';
import { useSignal } from '@vaadin/hilla-react-signals';
import { DateTimePicker } from '@vaadin/react-components/DateTimePicker.js';
import {
type DatePickerElement,
DateTimePicker,
type DateTimePickerElement,
type TimePickerElement,
} from '@vaadin/react-components';

// tag::snippet[]
function Example() {
useSignals(); // hidden-source-line
const errorMessage = useSignal('');
const value = useSignal(addDays(new Date(), 7));
const minDate = useSignal(new Date());
const maxDate = useSignal(addDays(new Date(), 60));

return (
<DateTimePicker
label="Appointment date and time"
helperText="Must be within 60 days from today"
value={format(value.value, "yyyy-MM-dd'T'HH:00:00")}
Copy link
Contributor Author

@vursen vursen Sep 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The similar DatePicker and TimePicker examples don't have an initial value, so I decided that it's unnecessary for the DateTimePicker example too. This example seems to already contain a lot due to the validated listener.

min={format(minDate.value, "yyyy-MM-dd'T'HH:00:00")}
max={format(maxDate.value, "yyyy-MM-dd'T'HH:00:00")}
min={format(minDate.value, `yyyy-MM-dd'T'HH:00:00`)}
max={format(maxDate.value, `yyyy-MM-dd'T'HH:00:00`)}
errorMessage={errorMessage.value}
onValueChanged={({ detail: { value: newValue } }) => {
const date = parseISO(newValue ?? '');
value.value = date;
if (isBefore(date, minDate.value)) {
onValidated={(event) => {
const field = event.target as DateTimePickerElement;
const datePicker: DatePickerElement = field.querySelector('[slot=date-picker]')!;
const timePicker: TimePickerElement = field.querySelector('[slot=time-picker]')!;
const hasBadDateInput =
!datePicker.value && !!(datePicker.inputElement as HTMLInputElement).value;
const hasBadTimeInput =
!timePicker.value && !!(timePicker.inputElement as HTMLInputElement).value;

if (hasBadDateInput || hasBadTimeInput) {
errorMessage.value = 'Invalid date or time';
} else if (!field.value) {
errorMessage.value = 'Field is required';
} else if (field.value < field.min!) {
errorMessage.value = 'Too early, choose another date and time';
} else if (isAfter(date, maxDate.value)) {
} else if (field.value > field.max!) {
errorMessage.value = 'Too late, choose another date and time';
} else {
errorMessage.value = '';
Expand Down
21 changes: 18 additions & 3 deletions frontend/demo/component/emailfield/email-field-validation.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import 'Frontend/demo/init'; // hidden-source-line
import '@vaadin/email-field';
import { html, LitElement } from 'lit';
import { customElement } from 'lit/decorators.js';
import { customElement, state } from 'lit/decorators.js';
import type { EmailField, EmailFieldValidatedEvent } from '@vaadin/email-field';
import { applyTheme } from 'Frontend/generated/theme';

@customElement('email-field-validation')
Expand All @@ -13,15 +14,29 @@ export class Example extends LitElement {
return root;
}

@state()
private errorMessage = '';

protected override render() {
return html`
<!-- tag::snippet[] -->
<vaadin-email-field
pattern="^.+@example\\.com$"
required
pattern="^[a-zA-Z0-9_\\-+]+(?:\\.[a-zA-Z0-9_\\-+]+)*@example\\.com$"
label="Email address"
error-message="Enter a valid example.com email address"
helper-text="Only example.com addresses allowed"
.errorMessage="${this.errorMessage}"
@validated="${(event: EmailFieldValidatedEvent) => {
const field = event.target as EmailField;
const { validity } = field.inputElement as HTMLInputElement;
if (validity.valueMissing) {
this.errorMessage = 'Field is required';
} else if (validity.patternMismatch) {
this.errorMessage = 'Enter a valid example.com email address';
} else {
this.errorMessage = '';
}
}}"
></vaadin-email-field>
<!-- end::snippet[] -->
`;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,32 @@
import { reactExample } from 'Frontend/demo/react-example'; // hidden-source-line
import React from 'react';
import { EmailField } from '@vaadin/react-components/EmailField.js';
import { useSignals } from '@preact/signals-react/runtime'; // hidden-source-line
import { useSignal } from '@vaadin/hilla-react-signals';
import { EmailField, type EmailFieldElement } from '@vaadin/react-components/EmailField.js';

function Example() {
useSignals(); // hidden-source-line
const errorMessage = useSignal('');

return (
// tag::snippet[]
<EmailField
pattern="^.+@example\.com$"
required
pattern="^[a-zA-Z0-9_\-+]+(?:\.[a-zA-Z0-9_\-+]+)*@example\.com$"
label="Email address"
errorMessage="Enter a valid example.com email address"
helperText="Only example.com addresses allowed"
errorMessage={errorMessage.value}
onValidated={(event) => {
const field = event.target as EmailFieldElement;
const { validity } = field.inputElement as HTMLInputElement;
if (validity.valueMissing) {
errorMessage.value = 'Field is required';
} else if (validity.patternMismatch) {
errorMessage.value = 'Enter a valid example.com email address';
} else {
errorMessage.value = '';
}
}}
/>
// end::snippet[]
);
Expand Down
18 changes: 17 additions & 1 deletion frontend/demo/component/numberfield/number-field-step.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import 'Frontend/demo/init'; // hidden-source-line
import '@vaadin/number-field';
import { html, LitElement } from 'lit';
import { customElement } from 'lit/decorators.js';
import { customElement, state } from 'lit/decorators.js';
import type { NumberField, NumberFieldValidatedEvent } from '@vaadin/number-field';
import { applyTheme } from 'Frontend/generated/theme';

@customElement('number-field-step')
Expand All @@ -13,6 +14,9 @@ export class Example extends LitElement {
return root;
}

@state()
private errorMessage = '';

protected override render() {
return html`
<!-- tag::snippet[] -->
Expand All @@ -21,6 +25,18 @@ export class Example extends LitElement {
step="0.5"
value="12.5"
step-buttons-visible
.errorMessage="${this.errorMessage}"
@validated="${(event: NumberFieldValidatedEvent) => {
const field = event.target as NumberField;
const { validity } = field.inputElement as HTMLInputElement;
if (validity.badInput) {
this.errorMessage = 'Invalid number format';
} else if (validity.stepMismatch) {
this.errorMessage = `Duration must be a multiple of ${field.step}`;
} else {
this.errorMessage = '';
}
}}"
></vaadin-number-field>
<!-- end::snippet[] -->
`;
Expand Down
25 changes: 23 additions & 2 deletions frontend/demo/component/numberfield/number-field-validation.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import 'Frontend/demo/init'; // hidden-source-line
import '@vaadin/integer-field';
import { html, LitElement } from 'lit';
import { customElement } from 'lit/decorators.js';
import { customElement, state } from 'lit/decorators.js';
import type { IntegerField, IntegerFieldValidatedEvent } from '@vaadin/integer-field';
import { applyTheme } from 'Frontend/generated/theme';

@customElement('number-field-validation')
Expand All @@ -13,16 +14,36 @@ export class Example extends LitElement {
return root;
}

@state()
private errorMessage = '';

protected override render() {
return html`
<!-- tag::snippet[] -->
<vaadin-integer-field
label="Quantity"
helper-text="Max 10 items"
min="0"
required
min="1"
max="10"
value="2"
step-buttons-visible
.errorMessage="${this.errorMessage}"
@validated="${(event: IntegerFieldValidatedEvent) => {
const field = event.target as IntegerField;
const { validity } = field.inputElement as HTMLInputElement;
if (validity.badInput) {
this.errorMessage = 'Invalid number format';
} else if (validity.valueMissing) {
this.errorMessage = 'Field is required';
} else if (validity.rangeUnderflow) {
this.errorMessage = `Quantity must be at least ${field.min}`;
} else if (validity.rangeOverflow) {
this.errorMessage = `Maximum ${field.max} items available`;
} else {
this.errorMessage = '';
}
}}"
></vaadin-integer-field>
<!-- end::snippet[] -->
`;
Expand Down
Loading
Loading