Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
ec83531
fix(input): add aria-live attributes to error text
ShaneK Aug 14, 2025
e358cab
Merge branch 'main' of github.com:ionic-team/ionic-framework into ion…
ShaneK Aug 19, 2025
a7295b4
fix(input): making validation reading work more consistently across b…
ShaneK Aug 19, 2025
fc05815
fix(lint): fixing lint in test files
ShaneK Aug 19, 2025
f1bb778
Merge branch 'main' of github.com:ionic-team/ionic-framework into ion…
ShaneK Aug 21, 2025
9ebada9
App validation tests
ShaneK Aug 21, 2025
1baf39e
fix(input): improve validation state reactivity
ShaneK Aug 21, 2025
5760856
fix(input): fixing input validation accessibility for template-driven…
ShaneK Aug 21, 2025
85b8cbf
fix(input): cleanup on input validation
ShaneK Aug 26, 2025
1d0c191
fix(cleanup): removing file
ShaneK Aug 26, 2025
65dd166
Restoring tests
ShaneK Aug 26, 2025
a9ff301
Merge branch 'main' of github.com:ionic-team/ionic-framework into ion…
ShaneK Sep 2, 2025
65867ce
refactor(input): removing debug code
ShaneK Sep 2, 2025
df8fa7d
refactor(input): removing angular-specific code from core
ShaneK Sep 2, 2025
0180454
fix(lint): fixing lint in core
ShaneK Sep 2, 2025
7fc8cbc
Update packages/angular/test/base/src/app/standalone/validation/input…
ShaneK Sep 3, 2025
2db2b1f
Update core/src/components/input/test/validation/index.html
ShaneK Sep 3, 2025
7926f08
Update core/src/components/textarea/test/validation/index.html
ShaneK Sep 3, 2025
1493bf7
refactor(tests, input): doing cleanup across input and tests
ShaneK Sep 4, 2025
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
59 changes: 51 additions & 8 deletions core/src/components/input/input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,15 @@ export class Input implements ComponentInterface {
*/
@State() hasFocus = false;

/**
* Track validation state for proper aria-live announcements
*/
@State() isInvalid = false;

@Element() el!: HTMLIonInputElement;

private validationObserver?: MutationObserver;

/**
* The color to use from your application's color palette.
* Default options are: `"primary"`, `"secondary"`, `"tertiary"`, `"success"`, `"warning"`, `"danger"`, `"light"`, `"medium"`, and `"dark"`.
Expand Down Expand Up @@ -396,6 +403,16 @@ export class Input implements ComponentInterface {
};
}

/**
* Checks if the input is in an invalid state based on Ionic validation classes
*/
private checkInvalidState(): boolean {
const hasIonTouched = this.el.classList.contains('ion-touched');
const hasIonInvalid = this.el.classList.contains('ion-invalid');

return hasIonTouched && hasIonInvalid;
}

connectedCallback() {
const { el } = this;

Expand All @@ -406,6 +423,26 @@ export class Input implements ComponentInterface {
() => this.labelSlot
);

// Watch for class changes to update validation state
if (Build.isBrowser && typeof MutationObserver !== 'undefined') {
this.validationObserver = new MutationObserver(() => {
const newIsInvalid = this.checkInvalidState();
if (this.isInvalid !== newIsInvalid) {
this.isInvalid = newIsInvalid;
// Force a re-render to update aria-describedby immediately
forceUpdate(this);
}
});

this.validationObserver.observe(el, {
attributes: true,
attributeFilter: ['class'],
});
}

// Always set initial state
this.isInvalid = this.checkInvalidState();

this.debounceChanged();
if (Build.isBrowser) {
document.dispatchEvent(
Expand Down Expand Up @@ -451,6 +488,12 @@ export class Input implements ComponentInterface {
this.notchController.destroy();
this.notchController = undefined;
}

// Clean up validation observer to prevent memory leaks
if (this.validationObserver) {
this.validationObserver.disconnect();
this.validationObserver = undefined;
}
}

/**
Expand Down Expand Up @@ -626,22 +669,22 @@ export class Input implements ComponentInterface {
* Renders the helper text or error text values
*/
private renderHintText() {
const { helperText, errorText, helperTextId, errorTextId } = this;
const { helperText, errorText, helperTextId, errorTextId, isInvalid } = this;

return [
<div id={helperTextId} class="helper-text">
{helperText}
<div id={helperTextId} class="helper-text" aria-live="polite">
{!isInvalid ? helperText : null}
</div>,
<div id={errorTextId} class="error-text">
{errorText}
<div id={errorTextId} class="error-text" role="alert">
{isInvalid ? errorText : null}
</div>,
];
}

private getHintTextID(): string | undefined {
const { el, helperText, errorText, helperTextId, errorTextId } = this;
const { isInvalid, helperText, errorText, helperTextId, errorTextId } = this;

if (el.classList.contains('ion-touched') && el.classList.contains('ion-invalid') && errorText) {
if (isInvalid && errorText) {
return errorTextId;
}

Expand Down Expand Up @@ -864,7 +907,7 @@ export class Input implements ComponentInterface {
onCompositionstart={this.onCompositionStart}
onCompositionend={this.onCompositionEnd}
aria-describedby={this.getHintTextID()}
aria-invalid={this.getHintTextID() === this.errorTextId}
aria-invalid={this.isInvalid ? 'true' : undefined}
{...this.inheritedAttributes}
/>
{this.clearInput && !readonly && !disabled && (
Expand Down
284 changes: 284 additions & 0 deletions core/src/components/input/test/validation/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,284 @@
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8" />
<title>Input - Validation</title>
<meta
name="viewport"
content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"
/>
<link href="../../../../../css/ionic.bundle.css" rel="stylesheet" />
<link href="../../../../../scripts/testing/styles.css" rel="stylesheet" />
<script src="../../../../../scripts/testing/scripts.js"></script>
<script nomodule src="../../../../../dist/ionic/ionic.js"></script>
<script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script>
<style>
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-row-gap: 20px;
grid-column-gap: 20px;
}

h2 {
font-size: 12px;
font-weight: normal;

color: var(--ion-color-step-600);

margin-top: 10px;
margin-bottom: 5px;
}

.validation-info {
margin: 20px;
padding: 10px;
background: var(--ion-color-light);
border-radius: 4px;
}
</style>
</head>

<body>
<ion-app>
<ion-header>
<ion-toolbar>
<ion-title>Input - Validation Test</ion-title>
</ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
<div class="validation-info">
<h2>Screen Reader Testing Instructions:</h2>
<ol>
<li>Enable your screen reader (VoiceOver, NVDA, JAWS, etc.)</li>
<li>Tab through the form fields</li>
<li>When you tab away from an empty required field, the error should be announced immediately</li>
<li>The error text should be announced BEFORE the next field is announced</li>
<li>Test in Chrome, Safari, and Firefox to verify consistent behavior</li>
</ol>
</div>

<div class="grid">
<div>
<h2>Required Email Field</h2>
<ion-input
id="email-input"
type="email"
label="Email"
label-placement="floating"
fill="outline"
placeholder="Enter your email"
helper-text="We'll never share your email"
error-text="Please enter a valid email address"
required
></ion-input>
</div>

<div>
<h2>Required Name Field</h2>
<ion-input
id="name-input"
type="text"
label="Full Name"
label-placement="floating"
fill="outline"
placeholder="Enter your full name"
helper-text="First and last name"
error-text="Name is required"
required
></ion-input>
</div>

<div>
<h2>Phone Number (Pattern Validation)</h2>
<ion-input
id="phone-input"
type="tel"
label="Phone"
label-placement="floating"
fill="outline"
placeholder="(555) 555-5555"
pattern="^\(\d{3}\) \d{3}-\d{4}$"
helper-text="Format: (555) 555-5555"
error-text="Please enter a valid phone number"
required
></ion-input>
</div>

<div>
<h2>Password (Min Length)</h2>
<ion-input
id="password-input"
type="password"
label="Password"
label-placement="floating"
fill="outline"
placeholder="Enter password"
minlength="8"
helper-text="At least 8 characters"
error-text="Password must be at least 8 characters"
required
></ion-input>
</div>

<div>
<h2>Age (Number Range)</h2>
<ion-input
id="age-input"
type="number"
label="Age"
label-placement="floating"
fill="outline"
placeholder="Enter your age"
min="18"
max="120"
helper-text="Must be 18 or older"
error-text="Please enter a valid age (18-120)"
required
></ion-input>
</div>

<div>
<h2>Optional Field (No Validation)</h2>
<ion-input
id="optional-input"
type="text"
label="Optional Info"
label-placement="floating"
fill="outline"
placeholder="This field is optional"
helper-text="You can skip this field"
></ion-input>
</div>
</div>

<div class="ion-padding">
<ion-button id="submit-btn" expand="block" disabled>Submit Form</ion-button>
<ion-button id="reset-btn" expand="block" fill="outline">Reset Form</ion-button>
</div>
</ion-content>
</ion-app>

<script>
// Simple validation logic
const inputs = document.querySelectorAll('ion-input');
const submitBtn = document.getElementById('submit-btn');
const resetBtn = document.getElementById('reset-btn');

// Track which fields have been touched
const touchedFields = new Set();

// Validation functions
const validators = {
'email-input': (value) => {
if (!value) return false;
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
},
'name-input': (value) => {
return value && value.trim().length > 0;
},
'phone-input': (value) => {
if (!value) return false;
return /^\(\d{3}\) \d{3}-\d{4}$/.test(value);
},
'password-input': (value) => {
return value && value.length >= 8;
},
'age-input': (value) => {
if (!value) return false;
const age = parseInt(value);
return age >= 18 && age <= 120;
},
'optional-input': () => true, // Always valid
};

function validateField(input) {
const inputId = input.id;
const value = input.value;
const isValid = validators[inputId] ? validators[inputId](value) : true;

// Only show validation state if field has been touched
if (touchedFields.has(inputId)) {
if (isValid) {
input.classList.remove('ion-invalid');
input.classList.add('ion-valid');
} else {
input.classList.remove('ion-valid');
input.classList.add('ion-invalid');
}
input.classList.add('ion-touched');
}

return isValid;
}

function validateForm() {
let allValid = true;
inputs.forEach((input) => {
if (input.id !== 'optional-input') {
const isValid = validateField(input);
if (!isValid) {
allValid = false;
}
}
});
submitBtn.disabled = !allValid;
return allValid;
}

// Add event listeners
inputs.forEach((input) => {
// Mark as touched on blur
input.addEventListener('ionBlur', (e) => {
touchedFields.add(input.id);
validateField(input);
validateForm();

const isInvalid = input.classList.contains('ion-invalid');
if (isInvalid) {
console.log('Field marked invalid:', input.label, input.errorText);
}
});

// Validate on input
input.addEventListener('ionInput', (e) => {
if (touchedFields.has(input.id)) {
validateField(input);
validateForm();
}
});

// Also validate on focus loss via native blur
input.addEventListener('focusout', (e) => {
// Small delay to ensure Ionic's classes are updated
setTimeout(() => {
touchedFields.add(input.id);
validateField(input);
validateForm();
}, 10);
});
});

// Reset button
resetBtn.addEventListener('click', () => {
inputs.forEach((input) => {
input.value = '';
input.classList.remove('ion-valid', 'ion-invalid', 'ion-touched');
});
touchedFields.clear();
submitBtn.disabled = true;
});

// Submit button
submitBtn.addEventListener('click', () => {
if (validateForm()) {
alert('Form submitted successfully!');
}
});

// Initial setup
validateForm();
</script>
</body>
</html>
Loading
Loading