react-native - 验证动态添加的输入
问题描述
我正在使用 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>
解决方案
我相信您可以使用trigger
api 调用来强制它验证字段
无法添加代码示例,因为我看不到您在此代码中动态添加字段的位置
推荐阅读
- node.js - 使用 Mongoose 和 Express 连接到 MongoDB 时出现“主机标识符中的错误斜线”
- javascript - 三元运算符条件
- node.js - 在 NodeJS 本地服务器上编辑 JSON 文件导致“Express Session”参数设置为未定义
- javascript - 如何仅从图像 url 将图像发送到服务器?
- c - 如何使用 Make 将目标文件编译到存档中
- reactjs - useContext 值未更新
- c - The strtok Function With char * Argument
- javascript - Vue.js 3 中的插槽继承
- python - id="loginbutton" name="login" tabindex="0" type="submit">... 在点 (600, 341) 不可点击。无法点击 Facebook 上的登录按钮
- object - 如何将构造函数的实例分配给变量?