Next.js Discord

Discord Forum

Number in form not accepting

Answered
QBit posted this in #help-forum
Open in Discord
lc-form.tsx
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
View full answer

20 Replies

can you show the formfield? @QBit
@Collin can you show the formfield? <@858742600550580234>
<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
where to put parseInt
and why not this params: { problemID: number }?
<Input type="number" placeholder="Enter ID here" {...field} />
try this
still not working
@Collin
try removing the .min
since it is already required because it doesnt have .optional
in FormSchema I changed the ID = z.string() and then in Input type="number" is working fine
how should I ensure that only natural nos get submitted? @Collin
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
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
okay