Added YUP validation on forms

This commit is contained in:
Pijus Kamandulis 2024-10-14 21:06:15 +03:00
parent efeeb10746
commit 06d70bbd70
12 changed files with 206 additions and 167 deletions

BIN
bun.lockb

Binary file not shown.

View File

@ -13,10 +13,12 @@
"@ckeditor/ckeditor5-react": "^9.3.0",
"@tanstack/react-form": "^0.33.0",
"@tanstack/react-router": "^1.62.0",
"@tanstack/yup-form-adapter": "^0.33.0",
"appwrite": "^16.0.2",
"classnames": "^2.5.1",
"react": "^18.3.1",
"react-dom": "^18.3.1"
"react-dom": "^18.3.1",
"yup": "^1.4.0"
},
"devDependencies": {
"@eslint/js": "^9.11.1",

View File

@ -16,25 +16,28 @@ const Button: React.FC<ButtonProps> = ({
children,
color = ButtonColor.Primary,
fullWidth = false,
disabled = false,
...props
}) => {
const buttonClass = classNames(
'flex justify-center rounded-md px-3 py-1.5 text-sm font-semibold leading-6 text-white shadow-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2',
'flex justify-center rounded-md px-3 py-1.5 text-sm font-semibold leading-6 shadow-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2',
{
'bg-indigo-600 hover:bg-indigo-500 focus-visible:outline-indigo-600':
color === ButtonColor.Primary,
color === ButtonColor.Primary && !disabled,
'bg-gray-600 hover:bg-gray-500 focus-visible:outline-gray-600':
color === ButtonColor.Secondary,
color === ButtonColor.Secondary && !disabled,
'bg-red-600 hover:bg-red-500 focus-visible:outline-red-600':
color === ButtonColor.Error,
color === ButtonColor.Error && !disabled,
'bg-green-600 hover:bg-green-500 focus-visible:outline-green-600':
color === ButtonColor.Success,
color === ButtonColor.Success && !disabled,
'bg-gray-300 text-gray-500 cursor-not-allowed dark:bg-nero-600': disabled,
'text-white': !disabled,
'w-full': fullWidth,
},
);
return (
<button className={buttonClass} {...props}>
<button className={buttonClass} disabled={disabled} {...props}>
{children}
</button>
);

View File

@ -1,11 +1,15 @@
import { ValidationError } from '@tanstack/react-form';
const Input = ({
label,
errors,
...props
}: React.DetailedHTMLProps<
React.InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
> & {
label?: string;
errors?: ValidationError[];
}) => {
return (
<div>
@ -18,6 +22,11 @@ const Input = ({
{...props}
/>
</div>
{errors?.map((error, key) => (
<em key={`${error}-${key}`} role="alert">
{error}
</em>
))}
</div>
);
};

View File

@ -2,6 +2,8 @@ import { useForm } from '@tanstack/react-form';
import { useEstimationsList } from '../../lib/context/estimationsList';
import Input from '../Input';
import Button from '../Button';
import { yupValidator } from '@tanstack/yup-form-adapter';
import * as yup from 'yup';
interface CreateEstimationSessionFormProps {
onCreated: () => void;
@ -21,6 +23,12 @@ const CreateEstimationSessionForm: React.FC<
});
onCreated();
},
validators: {
onChange: yup.object({
name: yup.string().label('Name').max(200).required(),
}),
},
validatorAdapter: yupValidator(),
});
return (
@ -36,21 +44,25 @@ const CreateEstimationSessionForm: React.FC<
form.handleSubmit();
}}
>
<form.Field
name="name"
children={(field) => (
<form.Field name="name">
{(field) => (
<Input
label="Name"
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
errors={field.state.meta.errors}
/>
)}
/>
<Button type="submit" fullWidth>
Create
</Button>
</form.Field>
<form.Subscribe selector={(state) => [state.canSubmit]}>
{([canSubmit]) => (
<Button type="submit" disabled={!canSubmit} fullWidth>
Create
</Button>
)}
</form.Subscribe>
</form>
</>
);

View File

@ -16,7 +16,7 @@ const route = getRouteApi('/_authenticated/estimate/session/$sessionId');
const Estimation: React.FC = () => {
const { sessionId } = route.useParams();
const estimationState = useEstimationContext();
const [isDrawerOpen, setDrawerOpen] = useState(false);
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
const [editingTicketId, setEditingTicketId] = useState<string>('');
useEffect(() => estimationState?.setSessionId(sessionId), [sessionId]);
@ -32,10 +32,10 @@ const Estimation: React.FC = () => {
createTicket,
updateTicket,
currentSessionData: {
tickets: tickets,
tickets,
sessionState: {
votesRevealed: revealed,
votes: votes,
votes,
currentPlayerVote,
currentTicket,
},
@ -49,10 +49,10 @@ const Estimation: React.FC = () => {
className="w-64 overflow-y-scroll bg-gray-50 p-4 dark:bg-nero-800"
tickets={tickets}
onSelectTicket={(ticket) => setActiveTicket(ticket.id)}
onAddTicket={() => setDrawerOpen(true)}
onAddTicket={() => setIsDrawerOpen(true)}
onEditTicket={(ticketId) => {
setEditingTicketId(ticketId);
setDrawerOpen(true);
setIsDrawerOpen(true);
}}
/>
@ -95,7 +95,7 @@ const Estimation: React.FC = () => {
<Drawer
isOpen={isDrawerOpen}
onClose={() => {
setDrawerOpen(false);
setIsDrawerOpen(false);
setEditingTicketId('');
}}
>
@ -110,7 +110,7 @@ const Estimation: React.FC = () => {
} else {
await createTicket(ticket);
}
setDrawerOpen(false);
setIsDrawerOpen(false);
}}
/>
</Drawer>

View File

@ -1,6 +1,8 @@
import { useForm } from '@tanstack/react-form';
import { Button, Input } from '../../../components';
import RichEditor from '../../../components/RichEditor';
import { yupValidator } from '@tanstack/yup-form-adapter';
import * as yup from 'yup';
interface EditTicketFormData {
name: string;
@ -16,7 +18,7 @@ const EditTicketForm: React.FC<EditTicketFormProps> = ({
initialData,
onSave,
}) => {
const form = useForm<EditTicketFormData>({
const form = useForm({
defaultValues: initialData ?? {
name: '',
content: '',
@ -24,6 +26,12 @@ const EditTicketForm: React.FC<EditTicketFormProps> = ({
onSubmit: async ({ value }) => {
await onSave(value);
},
validators: {
onChange: yup.object({
name: yup.string().label('Name').max(200).required(),
}),
},
validatorAdapter: yupValidator(),
});
return (
@ -37,9 +45,8 @@ const EditTicketForm: React.FC<EditTicketFormProps> = ({
form.handleSubmit();
}}
>
<form.Field
name="name"
children={(field) => (
<form.Field name="name">
{(field) => (
<Input
label="Name"
required
@ -47,22 +54,26 @@ const EditTicketForm: React.FC<EditTicketFormProps> = ({
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
errors={field.state.meta.errors}
/>
)}
/>
<form.Field
name="content"
children={(field) => (
</form.Field>
<form.Field name="content">
{(field) => (
<RichEditor
value={field.state.value}
onBlur={field.handleBlur}
onChange={(value) => field.handleChange(value)}
/>
)}
/>
<Button type="submit" fullWidth>
Save
</Button>
</form.Field>
<form.Subscribe selector={(state) => [state.canSubmit]}>
{([canSubmit]) => (
<Button type="submit" disabled={!canSubmit} fullWidth>
Update
</Button>
)}
</form.Subscribe>
</form>
</div>
);

View File

@ -21,9 +21,9 @@ const PlayerList: React.FC<PlayerListProps> = ({
<ul className="max-h-48 divide-y divide-gray-300 overflow-y-auto dark:divide-gray-600">
{players.length > 0 ? (
players.map((player, index) => (
players.map((player) => (
<li
key={index}
key={player.userId}
className="py-2 text-sm text-gray-900 dark:text-gray-100"
>
{player.name}

View File

@ -1,27 +0,0 @@
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}

View File

@ -1,4 +1,3 @@
import './Home.css';
import { getRouteApi, Link } from '@tanstack/react-router';
import { useUser } from '../lib/context/user';
import { useEstimationsList } from '../lib/context/estimationsList';
@ -16,7 +15,7 @@ function Home() {
const user = useUser();
const navigate = route.useNavigate();
const estimationsList = useEstimationsList();
const [isDrawerOpen, setDrawerOpen] = useState(false);
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
return (
<>
@ -47,12 +46,12 @@ function Home() {
}}
/>
)}
onAddItem={() => setDrawerOpen(true)}
onAddItem={() => setIsDrawerOpen(true)}
/>
</div>
<Drawer isOpen={isDrawerOpen} onClose={() => setDrawerOpen(false)}>
<CreateEstimationSessionForm onCreated={() => setDrawerOpen(false)} />
<Drawer isOpen={isDrawerOpen} onClose={() => setIsDrawerOpen(false)}>
<CreateEstimationSessionForm onCreated={() => setIsDrawerOpen(false)} />
</Drawer>
</>
);

View File

@ -1,6 +1,8 @@
import { useForm } from '@tanstack/react-form';
import { useUser } from '../lib/context/user';
import { Button, ButtonColor, Input } from '../components';
import { yupValidator } from '@tanstack/yup-form-adapter';
import * as yup from 'yup';
const Login = () => {
const user = useUser();
@ -12,96 +14,110 @@ const Login = () => {
onSubmit: async ({ value }) => {
console.log({ value });
},
validators: {
onChange: yup.object({
email: yup.string().label('Email').email().required(),
password: yup.string().label('Password').min(8).max(256).required(),
}),
},
validatorAdapter: yupValidator(),
});
return (
<>
<div className="flex min-h-full flex-1 flex-col justify-center px-6 py-12 lg:px-8">
<div className="sm:mx-auto sm:w-full sm:max-w-sm">
<h2 className="mt-10 text-center text-2xl font-bold leading-9 tracking-tight">
Sign in to your account
</h2>
</div>
<div className="mt-10 sm:mx-auto sm:w-full sm:max-w-sm">
<form className="space-y-6">
<form.Field
name="email"
children={(field) => (
<Input
label="Email address"
type="email"
autoComplete="email"
required
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
/>
)}
/>
<form.Field
name="password"
children={(field) => (
<Input
label="Password"
type="password"
autoComplete="current-password"
required
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
/>
)}
/>
<div>
<div className="flex items-center justify-between gap-4">
<Button
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
user.login(
form.state.values.email,
form.state.values.password,
);
}}
>
Sign in
</Button>
<Button
color={ButtonColor.Secondary}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
user.login(
form.state.values.email,
form.state.values.password,
);
}}
>
Register
</Button>
</div>
</div>
</form>
<p className="mt-10 text-center text-sm text-gray-500">
Don't want to create an account?{' '}
<a
href="#"
className="font-semibold leading-6 text-indigo-600 hover:text-indigo-500"
onClick={() => user.loginAsGuest()}
>
Sign in as a guest
</a>
</p>
</div>
<div className="flex min-h-full flex-1 flex-col justify-center px-6 py-12 lg:px-8">
<div className="sm:mx-auto sm:w-full sm:max-w-sm">
<h2 className="mt-10 text-center text-2xl font-bold leading-9 tracking-tight">
Sign in to your account
</h2>
</div>
</>
<div className="mt-10 sm:mx-auto sm:w-full sm:max-w-sm">
<form className="space-y-6">
<form.Field name="email">
{(field) => (
<Input
label="Email address"
type="email"
autoComplete="email"
required
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
errors={field.state.meta.errors}
/>
)}
</form.Field>
<form.Field name="password">
{(field) => (
<Input
label="Password"
type="password"
autoComplete="current-password"
required
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
errors={field.state.meta.errors}
/>
)}
</form.Field>
<form.Subscribe
selector={(state) => [state.canSubmit, state.isSubmitting]}
>
{([canSubmit, isSubmitting]) => (
<div>
{/* TODO: Add loader when submitting */}
<div className="flex items-center justify-between gap-4">
<Button
disabled={!canSubmit}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
user.login(
form.state.values.email,
form.state.values.password,
);
}}
>
Sign in
</Button>
<Button
disabled={!canSubmit}
color={ButtonColor.Secondary}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
user.register(
form.state.values.email,
form.state.values.password,
);
}}
>
Register
</Button>
</div>
</div>
)}
</form.Subscribe>
</form>
<p className="mt-10 text-center text-sm text-gray-500">
Don't want to create an account?{' '}
<a
href="#"
className="font-semibold leading-6 text-indigo-600 hover:text-indigo-500"
onClick={() => user.loginAsGuest()}
>
Sign in as a guest
</a>
</p>
</div>
</div>
);
};

View File

@ -1,6 +1,8 @@
import { useForm } from '@tanstack/react-form';
import { Button, Input } from '../components';
import { useUser } from '../lib/context/user';
import { yupValidator } from '@tanstack/yup-form-adapter';
import * as yup from 'yup';
const Profile = () => {
const user = useUser();
@ -12,6 +14,12 @@ const Profile = () => {
await user.updateUsername(value.name);
updateUsernameForm.reset();
},
validators: {
onChange: yup.object({
name: yup.string().label('Name').max(128).required(),
}),
},
validatorAdapter: yupValidator(),
});
return (
@ -28,21 +36,27 @@ const Profile = () => {
updateUsernameForm.handleSubmit();
}}
>
<updateUsernameForm.Field
name="name"
children={(field) => (
<Input
label="Name"
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
/>
<updateUsernameForm.Field name="name">
{(field) => {
return (
<Input
label="Name"
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onChange={(e) => field.handleChange(e.target.value)}
errors={field.state.meta.errors}
/>
);
}}
</updateUsernameForm.Field>
<updateUsernameForm.Subscribe selector={(state) => [state.canSubmit]}>
{([canSubmit]) => (
<Button type="submit" disabled={!canSubmit} fullWidth>
Update
</Button>
)}
/>
<Button type="submit" fullWidth>
Update
</Button>
</updateUsernameForm.Subscribe>
</form>
</div>
</div>