动态验证添加的输入



我使用nativebase和react hook表单进行表单验证,它工作得很好,但我有一个电话号码字段可以输入或通过点击一个模态的联系人项目填充的情况。当从联系人列表中填写时,我尝试提交,该字段未被验证,我无法提交,直到我输入触发onChangeText的字段。如何在动态添加输入时验证表单字段?下面是我的代码

import {
Input,
FormControl,
...
...
} from "native-base";
const {
control,
handleSubmit,
formState: { errors },
} = useForm();
<FormControl isRequired isInvalid={"customer" in errors}>
<Text color="gray.500" style={{fontFamily:fontFamily.semiBold, fontSize:14, marginBottom:5, left:3}}>Phone Number</Text>
<Controller
control={control}
rules={{
required: true,
}}
render={({ field: { onChange, onBlur, value } }) => 
(
<Input
value={formData.customer}
selectionColor="brand.500"

keyboardType="numeric"
variant="filled"
placeholder=""
_focus={{
borderColor: "brand.500",
}}
onBlur={onBlur}
InputRightElement={

<Button
style={{ backgroundColor: "transparent" 
}}
onPress={()=>{
setData((prevState) => ({
...prevState,
isVisibleShowContacts: true,
}));
}}
>
<Icon
style={{ left:5}}
color="gray.600"
size={6}
as={AntDesign}
name="contacts"
/>
</Button>
}

onChangeText={(val) => {
onChange(val);
setFormData((prevState) => ({
...prevState,
customer: val,
}));



}
}
/>
)}
name="customer"
defaultValue=""
/>
<FormControl.ErrorMessage>
{errors.customer && (
<Text
style={{
fontSize: 12,
textAlign: "right",
fontFamily: fontFamily.semiBold,
}}
>
Required
</Text>
)}
</FormControl.ErrorMessage>
</FormControl>
<Button
bgColor="brand.600"
style={{
marginTop: 30,
margin: 40,
borderRadius: 50,
elevation: 4,
}}

onPress={handleSubmit(submit)}

><Text
style={{
fontFamily: fontFamily.semiBold,
color: "white",
}}
>
Submit
</Text>

</Button>

我相信您可以使用triggerapi调用来强制它验证字段

  • https://react-hook-form.com/api/useform/trigger

不能添加代码示例,因为我不知道在这个代码中你动态添加字段

最新更新