@@ -2,7 +2,7 @@ import React, {useCallback, useMemo, useRef, useState, forwardRef} from 'react';
2
2
import { StyleSheet , NativeSyntheticEvent , TextInputKeyPressEventData } from 'react-native' ;
3
3
import { isUndefined , map } from 'lodash' ;
4
4
import { Constants } from '../../commons/new' ;
5
- import { useCombinedRefs } from '../../hooks' ;
5
+ import { useCombinedRefs , useDidUpdate } from '../../hooks' ;
6
6
import TextField , { TextFieldProps } from '../textField' ;
7
7
import Chip , { ChipProps } from '../chip' ;
8
8
@@ -50,6 +50,7 @@ const ChipsInput = forwardRef((props: ChipsInputProps, refToForward: React.Ref<a
50
50
onChange,
51
51
fieldStyle,
52
52
maxChips,
53
+ validate,
53
54
...others
54
55
} = props ;
55
56
const [ markedForRemoval , setMarkedForRemoval ] = useState < number | undefined > ( undefined ) ;
@@ -146,6 +147,37 @@ const ChipsInput = forwardRef((props: ChipsInputProps, refToForward: React.Ref<a
146
147
) ;
147
148
} , [ chips , leadingAccessory , defaultChipProps , removeMarkedChip , markedForRemoval , maxChips ] ) ;
148
149
150
+ const isRequired = useMemo ( ( ) => {
151
+ if ( ! validate ) {
152
+ return false ;
153
+ }
154
+
155
+ const inputValidators = Array . isArray ( validate ) ? validate : [ validate ] ;
156
+ return inputValidators . includes ( 'required' ) ;
157
+ } , [ validate ] ) ;
158
+
159
+ const requiredValidator = useCallback ( ( ) => {
160
+ return ! isRequired || ( chips ?. length ?? 0 ) > 0 ;
161
+ } , [ isRequired , chips ] ) ;
162
+
163
+ const _validate = useMemo ( ( ) => {
164
+ if ( ! validate ) {
165
+ return undefined ;
166
+ } else if ( isRequired ) {
167
+ const inputValidators = Array . isArray ( validate ) ? validate : [ validate ] ;
168
+ return inputValidators . map ( validator => ( validator === 'required' ? requiredValidator : validator ) ) ;
169
+ } else {
170
+ return validate ;
171
+ }
172
+ } , [ validate , isRequired , requiredValidator ] ) ;
173
+
174
+ useDidUpdate ( ( ) => {
175
+ if ( others . validateOnChange ) {
176
+ // @ts -expect-error
177
+ fieldRef . current ?. validate ( ) ;
178
+ }
179
+ } , [ chips , others . validateOnChange ] ) ;
180
+
149
181
return (
150
182
< TextField
151
183
// @ts -expect-error
@@ -159,6 +191,7 @@ const ChipsInput = forwardRef((props: ChipsInputProps, refToForward: React.Ref<a
159
191
fieldStyle = { [ fieldStyle , styles . fieldStyle ] }
160
192
onKeyPress = { onKeyPress }
161
193
accessibilityHint = { props . editable ? 'press keyboard delete button to remove last tag' : undefined }
194
+ validate = { _validate }
162
195
/>
163
196
) ;
164
197
} ) ;
0 commit comments