Number in form not accepting
Answered
QBit posted this in #help-forum
QBitOP
lc-form.tsx
page.tsx
How to resolve it?
const FormSchema = z.object({
ID: z.number().min(1, {
message: "Problem ID must be at least 1 character.",
}),
})
export function ProblemIDForm() {
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: {
ID: undefined,
},
})page.tsx
export default function ProblemID({
params,
}: {
params: { problemID: number }
}) {
return <div>Hello {params.problemID}</div>
}How to resolve it?
Answered by joulev
const id = Number.parseInt(params.problemId)
if (Number.isNaN(id)) {
// handle case when id is not a number
}
// use id instead of params.problemId here
if (Number.isNaN(id)) {
// handle case when id is not a number
}
// use id instead of params.problemId here
20 Replies
can you show the formfield? @QBit
dynamic params are string
@Collin can you show the formfield? <@858742600550580234>
QBitOP
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6">
<FormField
control={form.control}
name="ID"
render={({ field }) => (
<FormItem>
<FormLabel className="flex justify-center">Problem ID</FormLabel>
<FormControl>
<Input placeholder="Enter ID here" {...field} />
</FormControl>
<FormDescription>LeetCode problem ID</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<div className="flex justify-center">
<Button type="submit">Submit</Button>
</div>
</form>
</Form>@joulev `problemId` is a string. you need to `parseInt` it
QBitOP
where to put
parseIntand why not this
params: { problemID: number }?<Input type="number" placeholder="Enter ID here" {...field} />
try this
QBitOP
@Collin
try removing the .min
since it is already required because it doesnt have .optional
QBitOP
in
FormSchema I changed the ID = z.string() and then in Input type="number" is working finehow should I ensure that only natural nos get submitted? @Collin
QBitOP
okay
@QBit where to put `parseInt`
const id = Number.parseInt(params.problemId)
if (Number.isNaN(id)) {
// handle case when id is not a number
}
// use id instead of params.problemId here
if (Number.isNaN(id)) {
// handle case when id is not a number
}
// use id instead of params.problemId here
Answer
@QBit and why not this ` params: { problemID: number }`?
Nothing in nextjs guarantees problemId is a number. app/foo/[problemId]/bar/page.tsx catches /foo/1/bar, but it catches /foo/hello/bar too
QBitOP
okay