Skip to content
Example · Advanced

Validation

Validate time input and handle invalid entries

Built-in Validation

Timepicker-UI includes built-in validation that adds error classes to invalid inputs. Use event callbacks to implement custom validation logic.

Basic Validation

The timepicker automatically validates input format:

Custom Validation

Implement custom validation in the onConfirm callback:

Required Field

Validate that a time has been selected:

index.tstypescript
1import { TimepickerUI } from 'timepicker-ui';
2
3const input = document.querySelector('#timepicker');
4const form = document.querySelector('#myForm');
5const picker = new TimepickerUI(input);
6
7picker.create();
8
9form.addEventListener('submit', (e) => {
10 e.preventDefault();
11
12 if (!input.value) {
13 input.classList.add('error');
14
15 // Add error message
16 const errorMsg = document.createElement('div');
17 errorMsg.className = 'error-message';
18 errorMsg.textContent = 'Time is required';
19 input.parentElement.appendChild(errorMsg);
20
21 return;
22 }
23
24 input.classList.remove('error');
25 // Submit form
26 console.log('Form submitted with time:', input.value);
27});

Time Range Validation

Validate time is within a specific range:

index.tstypescript
1import { TimepickerUI } from 'timepicker-ui';
2
3function validateTimeRange(time: string, min: string, max: string): boolean {
4 const [timeH, timeM] = time.split(':').map(Number);
5 const [minH, minM] = min.split(':').map(Number);
6 const [maxH, maxM] = max.split(':').map(Number);
7
8 const timeMinutes = timeH * 60 + timeM;
9 const minMinutes = minH * 60 + minM;
10 const maxMinutes = maxH * 60 + maxM;
11
12 return timeMinutes >= minMinutes && timeMinutes <= maxMinutes;
13}
14
15const input = document.querySelector('#timepicker');
16const picker = new TimepickerUI(input, {
17 callbacks: {
18 onConfirm: (data) => {
19 const time = `${data.hour}:${data.minutes}`;
20
21 if (!validateTimeRange(time, '08:00', '18:00')) {
22 alert('Time must be between 8:00 AM and 6:00 PM');
23 input.classList.add('error');
24 return;
25 }
26
27 input.classList.remove('error');
28 }
29 }
30});
31
32picker.create();

React Form Integration

Integrate with React form validation libraries:

index.tsxtsx
1import { useEffect, useRef, useMemo } from 'react';
2import { TimepickerUI } from 'timepicker-ui';
3import { useForm } from 'react-hook-form';
4
5function TimePickerForm() {
6 const inputRef = useRef<HTMLInputElement>(null);
7 const pickerRef = useRef<TimepickerUI | null>(null);
8
9 const {
10 register,
11 handleSubmit,
12 setValue,
13 formState: { errors }
14 } = useForm();
15
16 const options = useMemo(() => ({
17 callbacks: {
18 onConfirm: (data) => {
19 const time = `${data.hour}:${data.minutes}${data.type ? ' ' + data.type : ''}`;
20 setValue('time', time, { shouldValidate: true });
21 }
22 }
23 }), [setValue]);
24
25 useEffect(() => {
26 if (!inputRef.current) return;
27
28 pickerRef.current = new TimepickerUI(inputRef.current, options);
29 pickerRef.current.create();
30
31 return () => {
32 pickerRef.current?.destroy();
33 };
34 }, []);
35
36 const onSubmit = (data) => {
37 console.log('Form data:', data);
38 };
39
40 return (
41 <form onSubmit={handleSubmit(onSubmit)}>
42 <input
43 ref={inputRef}
44 type="text"
45 {...register('time', {
46 required: 'Time is required',
47 pattern: {
48 value: /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/,
49 message: 'Invalid time format'
50 }
51 })}
52 />
53 {errors.time && (
54 <span className="error">{errors.time.message}</span>
55 )}
56 <button type="submit">Submit</button>
57 </form>
58 );
59}

Server-Side Validation

Handle validation errors from server responses:

index.tstypescript
1import { TimepickerUI } from 'timepicker-ui';
2
3const input = document.querySelector('#timepicker');
4const picker = new TimepickerUI(input);
5
6picker.create();
7
8async function submitTime(time: string) {
9 try {
10 const response = await fetch('/api/appointments', {
11 method: 'POST',
12 headers: { 'Content-Type': 'application/json' },
13 body: JSON.stringify({ time })
14 });
15
16 if (!response.ok) {
17 const error = await response.json();
18
19 // Show server validation error
20 input.classList.add('error');
21
22 const errorMsg = document.createElement('div');
23 errorMsg.className = 'error-message';
24 errorMsg.textContent = error.message;
25 input.parentElement.appendChild(errorMsg);
26
27 return;
28 }
29
30 console.log('Time saved successfully');
31 } catch (error) {
32 console.error('Validation error:', error);
33 }
34}