Как правильно настроить работу react-hook-form и Select из React-select?

При подключении react-hook-form не работает rules для валидации

import React, { useState } from 'react';
import { CustomSelect as Select } from '../Select/Select';
import { useForm, Controller } from 'react-hook-form';
import { Button } from '../Button/Button';

type TSelect = {
	value: string;
	label: string;
	name: string;
};

interface ISelectProps {
	options?: TSelect[];
}

export const DefaultSelect = ({ options = [] }: ISelectProps) => {
	const {
		handleSubmit,
		control,
		formState: { errors, isValid, touchedFields },
	} = useForm({ mode: 'onChange', criteriaMode: 'firstError' });
	const onSubmit = (data: any) => {
		console.log(data);
	};

	return (
		<>
			<Controller
				name='brand'
				control={control}
				render={({
					field: { onChange, onBlur, value, name, ref },
					fieldState: { invalid, isTouched, isDirty, error },
					formState,
				}) => {
					return (
						<Select
							caption='Марка авто'
							placeholder='Выберите марку'
							options={options}
							wrapClassName='filter_select_wrapper'
							value={value}
							onChange={onChange}
							onBlur={onBlur}
							refs={{ ref, name }}
						/>
					);
				}}
				rules={{
					validate: {
						required: value => value.trim().length > 0 || 'Input is required',
					},
					maxLength: {
						value: 5,
						message: 'Input cannot be more than 5 characters.',
					},
					pattern: {
						value: /^[^/\\:*?<>]+$/,
						message: 'Input cannot have the following characters: / \\ : * ? < >',
					},
				}}
			/>
			<Button onClick={handleSubmit(onSubmit)}>Отправить</Button>
		</>
	);
};


import React from 'react';
import CreatableSelect from 'react-select/creatable';
import { components } from 'react-select';
import clsx from 'clsx';
import { Typography } from '../Typography/Typography';
import { ISelectProps } from './types';
import { selectStyles } from './style';
import stylesTypography from '../Typography/Typography.module.scss';
import styles from './SelectCreatable.module.scss';

export const SelectCreatable = ({
	options = [],
	placeholder = 'Выберите',
	caption,
	errorText,
	wrapClassName,
	labelClassName,
	className,
	size = '100%',
	prefix,
	disabled = false,
	isLoading,
	refs,
	inputProps,
	...props
}: ISelectProps) => {
	const customStyles = selectStyles(errorText, size, options, prefix);

	const Input = (initialProps: any) => {
		const customInput = <components.Input {...initialProps} />;
		return prefix ? (
			<div className={styles.Control}>
				<Typography textStyle='textM' className={stylesTypography.Typography_text_secondary}>
					{prefix}
				</Typography>
				<div className={styles.Control_option}>{customInput}</div>
			</div>
		) : (
			customInput
		);
	};

	return (
		<div className={clsx(wrapClassName)}>
			<label className={labelClassName}>
				{caption && (
					<Typography textStyle='textS' className={styles.Select_label}>
						{caption}
					</Typography>
				)}
			</label>
			<div className={clsx(styles.Select_wrapper, disabled && styles.Select_wrapper_disabled)}>
				<CreatableSelect
					options={options}
					styles={customStyles}
					placeholder={placeholder}
					formatCreateLabel={() => null}
					loadingMessage={() => 'Загрузка данных'}
					isLoading={isLoading}
					isDisabled={disabled}
					components={{ Input }}
					{...refs}
					{...props}
				/>
			</div>
			{errorText && (
				<Typography textStyle='menuItem' className={styles.Select_error}>
					{errorText}
				</Typography>
			)}
		</div>
	);
};
  • Вопрос задан
  • 1348 просмотров
Пригласить эксперта
Ответы на вопрос 1
@wonderingpeanut
Привет.
В твоем коде validate.required всегда будет true.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы