CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mui--x-date-pickers

The community edition of the MUI X Date and Time Picker components.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

validation-utilities.mddocs/

Validation and Utilities

Validation functions, utility hooks, and helper components for enhanced picker functionality and custom implementations.

Capabilities

Validation Functions

validateDate

Validates date values against constraints and business rules.

/**
 * Validates a date value against constraints
 * @param props - Validation configuration properties
 * @returns Validation error message or null if valid
 */
function validateDate<TDate>(props: ValidateDateProps<TDate>): string | null;

interface ValidateDateProps<TDate> {
  /** Date value to validate */
  value: TDate | null;
  /** Minimum allowed date */
  minDate?: TDate;
  /** Maximum allowed date */
  maxDate?: TDate;
  /** If true, disable dates after today */
  disableFuture?: boolean;
  /** If true, disable dates before today */
  disablePast?: boolean;
  /** Function to disable specific dates */
  shouldDisableDate?: (day: TDate) => boolean;
  /** Date adapter instance */
  adapter: MuiPickersAdapter<TDate>;
  /** Timezone for validation */
  timezone: PickersTimezone;
}

validateTime

Validates time values against time constraints and business rules.

/**
 * Validates a time value against constraints
 * @param props - Time validation configuration properties
 * @returns Validation error message or null if valid
 */
function validateTime<TDate>(props: ValidateTimeProps<TDate>): string | null;

interface ValidateTimeProps<TDate> {
  /** Time value to validate */
  value: TDate | null;
  /** Minimum allowed time */
  minTime?: TDate;
  /** Maximum allowed time */
  maxTime?: TDate;
  /** Function to disable specific times */
  shouldDisableTime?: (value: TDate, view: TimeView) => boolean;
  /** Date adapter instance */
  adapter: MuiPickersAdapter<TDate>;
  /** Timezone for validation */
  timezone: PickersTimezone;
  /** Current view being validated */
  view?: TimeView;
}

type TimeView = 'hours' | 'minutes' | 'seconds';

validateDateTime

Validates date-time values against combined date and time constraints.

/**
 * Validates a date-time value against constraints
 * @param props - Date-time validation configuration properties
 * @returns Validation error message or null if valid
 */
function validateDateTime<TDate>(props: ValidateDateTimeProps<TDate>): string | null;

interface ValidateDateTimeProps<TDate> extends ValidateDateProps<TDate>, ValidateTimeProps<TDate> {
  /** Minimum allowed date-time */
  minDateTime?: TDate;
  /** Maximum allowed date-time */
  maxDateTime?: TDate;
}

extractValidationProps

Utility function to extract validation-related props from picker props.

/**
 * Extracts validation props from picker component props
 * @param props - Picker component props
 * @returns Object containing validation props and remaining props
 */
function extractValidationProps<TProps extends Record<string, any>>(
  props: TProps
): {
  validationProps: ValidationProps;
  otherProps: Omit<TProps, keyof ValidationProps>;
};

interface ValidationProps {
  minDate?: any;
  maxDate?: any;
  minTime?: any;
  maxTime?: any;
  minDateTime?: any;
  maxDateTime?: any;
  disableFuture?: boolean;
  disablePast?: boolean;
  shouldDisableDate?: (day: any) => boolean;
  shouldDisableTime?: (value: any, view: string) => boolean;
}

Validation Hook

useValidation

Hook for managing validation state and error handling in picker components.

/**
 * Hook for managing validation state in picker components
 * @param props - Validation hook configuration properties
 * @returns Validation state and handlers
 */
function useValidation<TValue, TError>(
  props: UseValidationProps<TValue, TError>
): UseValidationReturnValue<TError>;

interface UseValidationProps<TValue, TError> {
  /** Current value to validate */
  value: TValue;
  /** Validator function */
  validator: Validator<TValue, TError>;
  /** If true, run validation on mount */
  validateOnMount?: boolean;
  /** External validation error */
  externalError?: TError;
}

interface UseValidationReturnValue<TError> {
  /** Current validation error */
  validationError: TError;
  /** Function to trigger validation */
  validateValue: () => void;
  /** Function to clear validation error */
  clearValidationError: () => void;
  /** If true, validation has been run */
  hasValidationError: boolean;
}

type Validator<TValue, TError> = (value: TValue) => TError;

Utility Hooks

usePickerTranslations

Hook for accessing localized text for picker components.

/**
 * Hook for accessing picker translations and localized text
 * @returns Translation functions and localized strings
 */
function usePickerTranslations(): PickersTranslations;

interface PickersTranslations {
  /** Get localized calendar view label */
  getCalendarViewSwitchingButtonAriaLabel: (view: CalendarPickerView) => string;
  /** Get localized clock view label */
  getClockViewSwitchingButtonAriaLabel: (view: ClockPickerView) => string;
  /** Get localized date picker dialog label */
  getOpenDatePickerDialogue: (value: any, adapter: MuiPickersAdapter<any>) => string;
  /** Get localized time picker dialog label */
  getOpenTimePickerDialogue: (value: any, adapter: MuiPickersAdapter<any>) => string;
  /** Localized button labels */
  cancelButtonLabel: string;
  clearButtonLabel: string;
  okButtonLabel: string;
  todayButtonLabel: string;
  /** Localized toolbar titles */
  datePickerToolbarTitle: string;
  timePickerToolbarTitle: string;
  dateTimePickerToolbarTitle: string;
  /** Navigation labels */
  previousMonth: string;
  nextMonth: string;
}

type CalendarPickerView = 'year' | 'month' | 'day';
type ClockPickerView = 'hours' | 'minutes' | 'seconds';

usePickerAdapter

Hook for accessing the current date adapter from LocalizationProvider context.

/**
 * Hook for accessing the current date adapter
 * @returns Date adapter instance from context
 */
function usePickerAdapter<TDate>(): MuiPickersAdapter<TDate>;

useIsValidValue

Hook for checking if a picker value is valid.

/**
 * Hook for validating picker values
 * @param props - Validation configuration properties
 * @returns Boolean indicating if value is valid
 */
function useIsValidValue<TDate>(props: UseIsValidValueProps<TDate>): boolean;

interface UseIsValidValueProps<TDate> {
  /** Value to validate */
  value: TDate | null;
  /** Date adapter instance */
  adapter: MuiPickersAdapter<TDate>;
  /** Timezone for validation */
  timezone?: PickersTimezone;
  /** Additional validator function */
  validator?: (value: TDate | null) => string | null;
}

usePickerContext

Hook for accessing picker context values.

/**
 * Hook for accessing picker context
 * @returns Picker context values
 */
function usePickerContext<TDate>(): PickerContext<TDate>;

interface PickerContext<TDate> {
  /** Current picker value */
  value: TDate | null;
  /** If true, picker is open */
  open: boolean;
  /** Function to set picker open state */
  setOpen: (open: boolean) => void;
  /** Current view */
  view: string;
  /** Function to change view */
  setView: (view: string) => void;
  /** Date adapter instance */
  adapter: MuiPickersAdapter<TDate>;
  /** Current timezone */
  timezone: PickersTimezone;
}

usePickerActionsContext

Hook for accessing picker action handlers.

/**
 * Hook for accessing picker action context
 * @returns Picker action handlers
 */
function usePickerActionsContext(): PickerActionsContext;

interface PickerActionsContext {
  /** Accept current value and close picker */
  onAccept: () => void;
  /** Cancel selection and close picker */
  onCancel: () => void;
  /** Clear current value */
  onClear: () => void;
  /** Set current value to today */
  onSetToday: () => void;
}

useSplitFieldProps

Hook for splitting field props from other picker props.

/**
 * Hook for splitting field props from picker props
 * @param props - Combined picker and field props
 * @returns Object with separated field and picker props
 */
function useSplitFieldProps<TProps extends Record<string, any>>(
  props: TProps
): {
  fieldProps: FieldProps;
  pickerProps: Omit<TProps, keyof FieldProps>;
};

interface FieldProps {
  value?: any;
  defaultValue?: any;
  onChange?: (value: any, context: any) => void;
  format?: string;
  disabled?: boolean;
  readOnly?: boolean;
  required?: boolean;
  shouldRespectLeadingZeros?: boolean;
  selectedSections?: any;
  onSelectedSectionsChange?: (sections: any) => void;
}

useParsedFormat

Hook for parsing and validating date format strings.

/**
 * Hook for parsing date format strings
 * @param formatString - Date format string to parse
 * @returns Parsed format information
 */
function useParsedFormat(formatString: string): ParsedFormat;

interface ParsedFormat {
  /** Parsed format sections */
  sections: FormatSection[];
  /** If true, format is valid */
  isValid: boolean;
  /** Format validation error */
  error?: string;
}

interface FormatSection {
  /** Section type */
  type: FieldSectionType;
  /** Format token */
  token: string;
  /** Section length */
  length: number;
}

type FieldSectionType = 'year' | 'month' | 'day' | 'weekDay' | 'hours' | 'minutes' | 'seconds' | 'meridiem' | 'empty';

Manager Hooks

useDateManager

Hook for managing date field state and operations.

/**
 * Hook for managing date field state
 * @param props - Date manager configuration properties
 * @returns Date field state and handlers
 */
function useDateManager<TDate>(props: UseDateManagerParameters<TDate>): UseDateManagerReturnValue<TDate>;

interface UseDateManagerParameters<TDate> {
  /** Current date value */
  value?: TDate | null;
  /** Default date value */
  defaultValue?: TDate | null;
  /** Callback when date changes */
  onChange?: (value: TDate | null, context: FieldChangeContext<TDate>) => void;
  /** Date format string */
  format?: string;
  /** Date adapter instance */
  adapter: MuiPickersAdapter<TDate>;
  /** Validation rules */
  validation?: Partial<ValidateDateProps<TDate>>;
}

interface UseDateManagerReturnValue<TDate> {
  /** Current date value */
  value: TDate | null;
  /** Formatted date string */
  formattedValue: string;
  /** Date change handler */
  handleValueChange: (value: TDate | null) => void;
  /** Field sections */
  sections: FieldSection[];
  /** Active section index */
  activeSectionIndex: number | null;
  /** Validation error */
  validationError: string | null;
}

interface DateManagerFieldInternalProps<TDate> {
  value: TDate | null;
  onChange: (value: TDate | null, context: FieldChangeContext<TDate>) => void;
  format: string;
}

useTimeManager

Hook for managing time field state and operations.

/**
 * Hook for managing time field state
 * @param props - Time manager configuration properties
 * @returns Time field state and handlers
 */
function useTimeManager<TDate>(props: UseTimeManagerParameters<TDate>): UseTimeManagerReturnValue<TDate>;

interface UseTimeManagerParameters<TDate> {
  /** Current time value */
  value?: TDate | null;
  /** Default time value */
  defaultValue?: TDate | null;
  /** Callback when time changes */
  onChange?: (value: TDate | null, context: FieldChangeContext<TDate>) => void;
  /** Time format string */
  format?: string;
  /** Date adapter instance */
  adapter: MuiPickersAdapter<TDate>;
  /** If true, use 12-hour format */
  ampm?: boolean;
  /** Validation rules */
  validation?: Partial<ValidateTimeProps<TDate>>;
}

interface UseTimeManagerReturnValue<TDate> {
  /** Current time value */
  value: TDate | null;
  /** Formatted time string */
  formattedValue: string;
  /** Time change handler */
  handleValueChange: (value: TDate | null) => void;
  /** Field sections */
  sections: FieldSection[];
  /** Active section index */
  activeSectionIndex: number | null;
  /** Validation error */
  validationError: string | null;
}

interface TimeManagerFieldInternalProps<TDate> {
  value: TDate | null;
  onChange: (value: TDate | null, context: FieldChangeContext<TDate>) => void;
  format: string;
  ampm?: boolean;
}

useDateTimeManager

Hook for managing date-time field state and operations.

/**
 * Hook for managing date-time field state
 * @param props - Date-time manager configuration properties
 * @returns Date-time field state and handlers
 */
function useDateTimeManager<TDate>(props: UseDateTimeManagerParameters<TDate>): UseDateTimeManagerReturnValue<TDate>;

interface UseDateTimeManagerParameters<TDate> {
  /** Current date-time value */
  value?: TDate | null;
  /** Default date-time value */
  defaultValue?: TDate | null;
  /** Callback when date-time changes */
  onChange?: (value: TDate | null, context: FieldChangeContext<TDate>) => void;
  /** Date-time format string */
  format?: string;
  /** Date adapter instance */
  adapter: MuiPickersAdapter<TDate>;
  /** If true, use 12-hour format */
  ampm?: boolean;
  /** Validation rules */
  validation?: Partial<ValidateDateTimeProps<TDate>>;
}

interface UseDateTimeManagerReturnValue<TDate> {
  /** Current date-time value */
  value: TDate | null;
  /** Formatted date-time string */
  formattedValue: string;
  /** Date-time change handler */
  handleValueChange: (value: TDate | null) => void;
  /** Field sections */
  sections: FieldSection[];
  /** Active section index */
  activeSectionIndex: number | null;
  /** Validation error */
  validationError: string | null;
}

interface DateTimeManagerFieldInternalProps<TDate> {
  value: TDate | null;
  onChange: (value: TDate | null, context: FieldChangeContext<TDate>) => void;
  format: string;
  ampm?: boolean;
}

Usage Examples:

import {
  validateDate,
  validateTime,
  usePickerTranslations,
  usePickerAdapter,
  useIsValidValue,
  useDateManager
} from '@mui/x-date-pickers';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import dayjs, { Dayjs } from 'dayjs';

// Custom validation example
function CustomValidatedPicker() {
  const [value, setValue] = React.useState<Dayjs | null>(null);
  const adapter = usePickerAdapter();
  const translations = usePickerTranslations();
  
  const handleChange = (newValue: Dayjs | null) => {
    // Validate before setting
    const error = validateDate({
      value: newValue,
      minDate: dayjs(),
      disableFuture: false,
      disablePast: true,
      adapter,
      timezone: 'default'
    });
    
    if (!error) {
      setValue(newValue);
    } else {
      console.error('Validation error:', error);
    }
  };
  
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <div>
        <input
          type="text"
          placeholder="Enter date"
          onChange={(e) => {
            const parsed = adapter.parse(e.target.value, 'MM/DD/YYYY');
            handleChange(parsed);
          }}
        />
        <button onClick={() => setValue(dayjs())}>
          {translations.todayButtonLabel}
        </button>
      </div>
    </LocalizationProvider>
  );
}

// Using date manager hook
function CustomDateField() {
  const adapter = usePickerAdapter();
  const {
    value,
    formattedValue,
    handleValueChange,
    sections,
    validationError
  } = useDateManager({
    value: null,
    onChange: (newValue) => console.log('Date changed:', newValue),
    format: 'MM/DD/YYYY',
    adapter,
    validation: {
      disablePast: true,
      minDate: dayjs(),
    }
  });
  
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <div>
        <input 
          value={formattedValue}
          onChange={(e) => {
            const parsed = adapter.parse(e.target.value, 'MM/DD/YYYY');
            handleValueChange(parsed);
          }}
        />
        {validationError && (
          <div style={{ color: 'red' }}>{validationError}</div>
        )}
      </div>
    </LocalizationProvider>
  );
}

Shared Types

interface FieldChangeContext<TDate> {
  validationError: string | null;
}

type PickersTimezone = string | 'default' | 'system';

interface FieldSection {
  value: string;
  format: string;
  maxLength: number | null;
  placeholder: string;
  type: FieldSectionType;
  contentType: FieldSectionContentType;
  hasLeadingZerosInFormat: boolean;
  hasLeadingZerosInInput: boolean;
  modified: boolean;
  startSeparator: string;
  endSeparator: string;
  isEndFormatSeparator?: boolean;
}

type FieldSectionType = 'year' | 'month' | 'day' | 'weekDay' | 'hours' | 'minutes' | 'seconds' | 'meridiem' | 'empty';
type FieldSectionContentType = 'digit' | 'digit-with-letter' | 'letter';

docs

adapters-localization.md

calendar-clock-components.md

date-pickers.md

datetime-pickers.md

field-components.md

index.md

time-pickers.md

validation-utilities.md

tile.json