0
# Input Handling and Validation
1
2
Comprehensive input support including various input types, validation, and input state management for creating interactive forms within popups.
3
4
## Capabilities
5
6
### Input Element Access
7
8
Methods to access and control input elements within popups.
9
10
```typescript { .api }
11
/**
12
* Gets the input DOM node, works with input parameter
13
* @returns The input element or null if no input is present
14
*/
15
function getInput(): HTMLInputElement | null;
16
17
/**
18
* Disables the popup input. A disabled input element is unusable and un-clickable
19
*/
20
function disableInput(): void;
21
22
/**
23
* Enables the popup input
24
*/
25
function enableInput(): void;
26
```
27
28
**Usage Examples:**
29
30
```typescript
31
// Access and modify input
32
Swal.fire({
33
title: 'Enter your name',
34
input: 'text',
35
didOpen: () => {
36
const input = Swal.getInput();
37
if (input) {
38
input.style.border = '2px solid #007bff';
39
input.addEventListener('focus', () => {
40
input.style.borderColor = '#28a745';
41
});
42
}
43
}
44
});
45
46
// Conditional input enabling
47
Swal.fire({
48
title: 'Account Setup',
49
html: `
50
<label>
51
<input type="checkbox" id="terms-checkbox"> I accept the terms
52
</label>
53
`,
54
input: 'text',
55
inputPlaceholder: 'Enter username',
56
didOpen: () => {
57
Swal.disableInput();
58
59
const checkbox = document.getElementById('terms-checkbox');
60
checkbox.addEventListener('change', (e) => {
61
if (e.target.checked) {
62
Swal.enableInput();
63
} else {
64
Swal.disableInput();
65
}
66
});
67
}
68
});
69
```
70
71
### Validation Messages
72
73
Methods to display and manage validation feedback.
74
75
```typescript { .api }
76
/**
77
* Shows a validation message
78
* @param validationMessage - The validation message text to display
79
*/
80
function showValidationMessage(validationMessage: string): void;
81
82
/**
83
* Hides validation message
84
*/
85
function resetValidationMessage(): void;
86
87
/**
88
* Gets the validation message container
89
* @returns The validation message element or null if not present
90
*/
91
function getValidationMessage(): HTMLElement | null;
92
```
93
94
**Usage Examples:**
95
96
```typescript
97
// Real-time validation
98
Swal.fire({
99
title: 'Email Validation',
100
input: 'email',
101
inputPlaceholder: 'Enter your email',
102
didOpen: () => {
103
const input = Swal.getInput();
104
if (input) {
105
input.addEventListener('input', (e) => {
106
const email = e.target.value;
107
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
108
109
if (email && !emailRegex.test(email)) {
110
Swal.showValidationMessage('Please enter a valid email address');
111
} else {
112
Swal.resetValidationMessage();
113
}
114
});
115
}
116
}
117
});
118
119
// Custom validation message styling
120
Swal.fire({
121
title: 'Password',
122
input: 'password',
123
inputValidator: (value) => {
124
if (!value) {
125
return 'Password is required';
126
}
127
if (value.length < 8) {
128
return 'Password must be at least 8 characters';
129
}
130
},
131
didOpen: () => {
132
const validationMsg = Swal.getValidationMessage();
133
if (validationMsg) {
134
validationMsg.style.fontSize = '14px';
135
validationMsg.style.fontWeight = 'bold';
136
}
137
}
138
});
139
```
140
141
## Input Types and Configuration
142
143
SweetAlert2 supports various input types through the `input` option in `SweetAlertOptions`.
144
145
```typescript { .api }
146
type SweetAlertInput =
147
| 'text' // Text input
148
| 'email' // Email input with validation
149
| 'password' // Password input (masked)
150
| 'number' // Numeric input
151
| 'tel' // Telephone input
152
| 'search' // Search input
153
| 'range' // Range slider
154
| 'textarea' // Multi-line text area
155
| 'select' // Dropdown select
156
| 'radio' // Radio button group
157
| 'checkbox' // Checkbox input
158
| 'file' // File upload
159
| 'url' // URL input with validation
160
| 'date' // Date picker
161
| 'datetime-local' // Date and time picker
162
| 'time' // Time picker
163
| 'week' // Week picker
164
| 'month'; // Month picker
165
```
166
167
### Text-based Inputs
168
169
```typescript
170
// Text input with validation
171
const { value: username } = await Swal.fire({
172
title: 'Enter username',
173
input: 'text',
174
inputLabel: 'Username',
175
inputPlaceholder: 'Your username',
176
inputAttributes: {
177
'maxlength': '20',
178
'autocomplete': 'username'
179
},
180
inputValidator: (value) => {
181
if (!value) {
182
return 'Username is required!';
183
}
184
if (value.length < 3) {
185
return 'Username must be at least 3 characters!';
186
}
187
if (!/^[a-zA-Z0-9_]+$/.test(value)) {
188
return 'Username can only contain letters, numbers, and underscores!';
189
}
190
}
191
});
192
193
// Email input
194
const { value: email } = await Swal.fire({
195
title: 'Email address',
196
input: 'email',
197
inputLabel: 'Your email address',
198
inputPlaceholder: 'user@example.com',
199
validationMessage: 'Please enter a valid email address'
200
});
201
202
// Password input
203
const { value: password } = await Swal.fire({
204
title: 'Enter password',
205
input: 'password',
206
inputLabel: 'Password',
207
inputPlaceholder: 'Your password',
208
inputValidator: (value) => {
209
if (!value) return 'Password is required';
210
if (value.length < 8) return 'Password must be at least 8 characters';
211
if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(value)) {
212
return 'Password must contain uppercase, lowercase, and number';
213
}
214
}
215
});
216
217
// Textarea
218
const { value: message } = await Swal.fire({
219
title: 'Your message',
220
input: 'textarea',
221
inputLabel: 'Message',
222
inputPlaceholder: 'Type your message here...',
223
inputAttributes: {
224
'rows': '5',
225
'maxlength': '500'
226
}
227
});
228
```
229
230
### Selection Inputs
231
232
```typescript
233
// Select dropdown
234
const { value: country } = await Swal.fire({
235
title: 'Select your country',
236
input: 'select',
237
inputOptions: {
238
'US': 'United States',
239
'CA': 'Canada',
240
'UK': 'United Kingdom',
241
'DE': 'Germany',
242
'FR': 'France'
243
},
244
inputPlaceholder: 'Choose a country',
245
inputValidator: (value) => {
246
if (!value) {
247
return 'Please select a country!';
248
}
249
}
250
});
251
252
// Radio buttons
253
const { value: size } = await Swal.fire({
254
title: 'Select size',
255
input: 'radio',
256
inputOptions: {
257
'small': 'Small',
258
'medium': 'Medium',
259
'large': 'Large',
260
'xlarge': 'Extra Large'
261
},
262
inputValidator: (value) => {
263
if (!value) {
264
return 'Please select a size!';
265
}
266
}
267
});
268
269
// Checkbox
270
const { value: agreement } = await Swal.fire({
271
title: 'Terms and Conditions',
272
input: 'checkbox',
273
inputValue: 0,
274
inputPlaceholder: 'I agree to the terms and conditions',
275
inputValidator: (value) => {
276
if (!value) {
277
return 'You must accept the terms and conditions!';
278
}
279
}
280
});
281
```
282
283
### Date and Time Inputs
284
285
```typescript
286
// Date picker
287
const { value: birthDate } = await Swal.fire({
288
title: 'Birth date',
289
input: 'date',
290
inputLabel: 'When were you born?',
291
inputAttributes: {
292
'min': '1900-01-01',
293
'max': new Date().toISOString().split('T')[0]
294
},
295
inputValidator: (value) => {
296
if (!value) return 'Please select your birth date';
297
const date = new Date(value);
298
const today = new Date();
299
if (date > today) return 'Birth date cannot be in the future';
300
}
301
});
302
303
// Time picker
304
const { value: meetingTime } = await Swal.fire({
305
title: 'Meeting time',
306
input: 'time',
307
inputLabel: 'Select meeting time',
308
inputValue: '09:00',
309
inputAttributes: {
310
'min': '08:00',
311
'max': '18:00'
312
}
313
});
314
315
// DateTime local
316
const { value: appointment } = await Swal.fire({
317
title: 'Schedule appointment',
318
input: 'datetime-local',
319
inputLabel: 'Appointment date and time',
320
inputAttributes: {
321
'min': new Date().toISOString().slice(0, 16)
322
}
323
});
324
```
325
326
### File Input
327
328
```typescript
329
// File upload
330
const { value: file } = await Swal.fire({
331
title: 'Upload file',
332
input: 'file',
333
inputLabel: 'Select a file to upload',
334
inputAttributes: {
335
'accept': 'image/*,.pdf,.doc,.docx',
336
'multiple': false
337
},
338
inputValidator: (file) => {
339
if (!file) {
340
return 'Please select a file!';
341
}
342
if (file.size > 10 * 1024 * 1024) { // 10MB
343
return 'File size must be less than 10MB!';
344
}
345
}
346
});
347
348
if (file) {
349
console.log('Selected file:', file.name, file.size, 'bytes');
350
}
351
```
352
353
### Range Input
354
355
```typescript
356
// Range slider
357
const { value: volume } = await Swal.fire({
358
title: 'Set volume',
359
input: 'range',
360
inputLabel: 'Volume level',
361
inputAttributes: {
362
'min': '0',
363
'max': '100',
364
'step': '5'
365
},
366
inputValue: 50,
367
didOpen: () => {
368
const input = Swal.getInput();
369
const output = document.createElement('output');
370
output.style.display = 'block';
371
output.style.marginTop = '10px';
372
output.style.fontSize = '18px';
373
output.style.fontWeight = 'bold';
374
output.textContent = input.value + '%';
375
376
input.parentNode.appendChild(output);
377
378
input.addEventListener('input', (e) => {
379
output.textContent = e.target.value + '%';
380
});
381
}
382
});
383
```
384
385
## Advanced Input Validation
386
387
```typescript
388
// Multi-field validation
389
const result = await Swal.fire({
390
title: 'Registration Form',
391
html: `
392
<input id="reg-username" class="swal2-input" placeholder="Username" maxlength="20">
393
<input id="reg-email" class="swal2-input" type="email" placeholder="Email">
394
<input id="reg-password" class="swal2-input" type="password" placeholder="Password">
395
<input id="reg-confirm" class="swal2-input" type="password" placeholder="Confirm Password">
396
`,
397
focusConfirm: false,
398
showCancelButton: true,
399
confirmButtonText: 'Register',
400
preConfirm: () => {
401
const username = document.getElementById('reg-username').value;
402
const email = document.getElementById('reg-email').value;
403
const password = document.getElementById('reg-password').value;
404
const confirm = document.getElementById('reg-confirm').value;
405
406
// Validation
407
if (!username) {
408
Swal.showValidationMessage('Username is required');
409
return false;
410
}
411
if (username.length < 3) {
412
Swal.showValidationMessage('Username must be at least 3 characters');
413
return false;
414
}
415
if (!email) {
416
Swal.showValidationMessage('Email is required');
417
return false;
418
}
419
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
420
Swal.showValidationMessage('Please enter a valid email');
421
return false;
422
}
423
if (!password) {
424
Swal.showValidationMessage('Password is required');
425
return false;
426
}
427
if (password.length < 8) {
428
Swal.showValidationMessage('Password must be at least 8 characters');
429
return false;
430
}
431
if (password !== confirm) {
432
Swal.showValidationMessage('Passwords do not match');
433
return false;
434
}
435
436
return { username, email, password };
437
}
438
});
439
440
if (result.isConfirmed) {
441
console.log('Registration data:', result.value);
442
}
443
444
// Async validation
445
const { value: apiKey } = await Swal.fire({
446
title: 'API Key Validation',
447
input: 'text',
448
inputLabel: 'Enter your API key',
449
inputPlaceholder: 'sk-...',
450
showLoaderOnConfirm: true,
451
preConfirm: async (apiKey) => {
452
try {
453
// Simulate API validation
454
const response = await fetch('/api/validate-key', {
455
method: 'POST',
456
headers: { 'Content-Type': 'application/json' },
457
body: JSON.stringify({ key: apiKey })
458
});
459
460
if (!response.ok) {
461
throw new Error('Invalid API key');
462
}
463
464
return apiKey;
465
} catch (error) {
466
Swal.showValidationMessage(`Validation failed: ${error.message}`);
467
return false;
468
}
469
}
470
});
471
```
472
473
## Input Configuration Options
474
475
All input-related options available in `SweetAlertOptions`:
476
477
```typescript { .api }
478
interface InputOptions {
479
input?: SweetAlertInput;
480
inputValue?: SyncOrAsync<string | number | File | FileList> | null;
481
inputPlaceholder?: string;
482
inputLabel?: string;
483
inputOptions?: SyncOrAsync<ReadonlyMap<string, string> | Record<string, any>>;
484
inputAutoTrim?: boolean;
485
inputAutoFocus?: boolean;
486
inputAttributes?: Record<string, string>;
487
inputValidator?: (value: any) => SyncOrAsync<string | null | false | void>;
488
validationMessage?: string;
489
returnInputValueOnDeny?: boolean;
490
}
491
```