import {
Box,
Flex,
Button,
FormControl,
FormErrorMessage,
FormLabel,
Input,
InputGroup,
InputLeftElement,
InputRightElement,
} from "@chakra-ui/react";
import { useForm } from "react-hook-form";
import { ReactNode, useCallback, useEffect, useState } from "react";
type arrType = {
arr: string[]
}
const ED = () => {
const [arr, setArr] = useState<any>([''])
const {
register,
handleSubmit,
trigger,
// watch,
setValue,
formState: { errors },
getValues,
} = useForm<arrType>({
mode: "onBlur"
});
const formSubmitHandle = useCallback(
async (v:any) => {
debugger
},
[]
);
return (
<Box>
<form onSubmit={handleSubmit(formSubmitHandle)}>
{arr.map((item: string, index: number) => {
return (
<FormControl mt={'44px'} isInvalid={!!errors[`arr`]? !!errors[`arr`][index]: false} key={index}>
<InputGroup h={'40px'} mt={'30px'}>
<Input
placeholder="输入手机号"
w={"340px"}
h={"100%"}
backgroundColor={"#F9F9FD"}
border={"1px solid #DEE0E2"}
{...register(`arr.${index}`, {
required: "手机号码不能为空",
pattern: {
value: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/,
message: "手机号码格式错误,请重新输入",
},
})}
onChange={() => {
}}
></Input>
</InputGroup>
<FormErrorMessage position={"absolute"} fontSize="xs">
{!!errors[`arr`] && errors[`arr`][index] && errors[`arr`][index]?.message as ReactNode}
</FormErrorMessage>
</FormControl>
)
})}
<Button
type="submit"
mt={"40px"}
w={"340px"}
h={"40px"}
background={'#2753FF'}
borderRadius={"20px"}
>
提交
</Button>
</form>
</Box>
)
}
export default ED;
chakra-ui useForm 数组动态遍历FormControl组件 表单验证 TS react nextjs
最新推荐文章于 2024-11-08 11:15:03 发布
本文介绍了如何使用Chakra-UI和ReactHookForm构建一个表单,实现动态数组输入,每个输入项进行手机号码格式验证,确保数据的准确性。
摘要由CSDN通过智能技术生成