Skip to content

Commit a13ff90

Browse files
committed
add validation for login and sign up pages
1 parent a72914b commit a13ff90

File tree

2 files changed

+35
-15
lines changed

2 files changed

+35
-15
lines changed

src/components/auth/Login.tsx

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import React from "react";
2-
import { useForm } from "@mantine/form";
2+
import { useForm, zodResolver } from "@mantine/form";
33
import {
44
Button,
55
Group,
@@ -8,11 +8,14 @@ import {
88
TextInput,
99
Title,
1010
} from "@mantine/core";
11+
import { z } from "zod";
1112

12-
export type LoginFields = {
13-
email: string;
14-
password: string;
15-
};
13+
const schema = z.object({
14+
email: z.string().email(),
15+
password: z.string().min(6),
16+
});
17+
18+
export type LoginFields = z.infer<typeof schema>;
1619

1720
type Props = {
1821
onSubmit: (f: LoginFields) => void;
@@ -26,12 +29,14 @@ const Login = (props: Props) => {
2629
email: "",
2730
password: "",
2831
},
32+
33+
validate: zodResolver(schema),
2934
});
3035

3136
return (
3237
<Stack m="md" w="50%">
3338
<Title order={1}>Welcome,</Title>
34-
<form onSubmit={() => onSubmit(form.values)}>
39+
<form onSubmit={form.onSubmit((values) => onSubmit(values))}>
3540
<TextInput
3641
withAsterisk
3742
label="Email"

src/components/auth/Signup.tsx

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,28 @@ import {
77
TextInput,
88
Title,
99
} from "@mantine/core";
10-
import { useForm } from "@mantine/form";
10+
import { useForm, zodResolver } from "@mantine/form";
11+
import { z } from "zod";
1112

12-
export type SignupFields = {
13-
name: string;
14-
committee: string;
15-
email: string;
16-
password: string;
17-
confirmPassword: string;
18-
};
13+
const schema = z
14+
.object({
15+
name: z.string().nonempty({ message: "Required" }),
16+
committee: z.string().nonempty({ message: "Required" }),
17+
email: z.string().email().nonempty({ message: "Required" }),
18+
password: z.string().min(6),
19+
confirmPassword: z.string().nonempty({ message: "Required" }),
20+
})
21+
.superRefine(({ confirmPassword, password }, ctx) => {
22+
if (confirmPassword !== password) {
23+
ctx.addIssue({
24+
code: "custom",
25+
message: "Password did not match",
26+
path: ["confirmPassword"],
27+
});
28+
}
29+
});
30+
31+
export type SignupFields = z.infer<typeof schema>;
1932

2033
type Props = {
2134
onSubmit: (f: SignupFields) => void;
@@ -32,12 +45,14 @@ const Signup = (props: Props) => {
3245
password: "",
3346
confirmPassword: "",
3447
},
48+
49+
validate: zodResolver(schema),
3550
});
3651

3752
return (
3853
<Stack m="md" w="50%">
3954
<Title order={1}>Welcome,</Title>
40-
<form onSubmit={() => onSubmit(form.values)}>
55+
<form onSubmit={form.onSubmit((values) => onSubmit(values))}>
4156
<TextInput
4257
withAsterisk
4358
label="Name"

0 commit comments

Comments
 (0)