Skip to content

Commit

Permalink
docs: dependent validation (fixes #126)
Browse files Browse the repository at this point in the history
  • Loading branch information
MiroslavPetrik committed Dec 4, 2024
1 parent bee4dda commit c15d703
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 19 deletions.
Original file line number Diff line number Diff line change
@@ -1,41 +1,63 @@
import { InputField } from "form-atoms";
import { zodValidate } from "form-atoms/zod";
import { z } from "zod";

import { FieldErrors, FieldLabel } from "../../components";
import { numberField } from "../../fields/number-field";
import { NumberInput } from "../../fields/number-field/NumberInput.mock";
import { textField } from "../../fields/text-field";
import { formStory, meta } from "../StoryForm";

export default {
...meta,
title: "guides/PasswordValidation",
title: "scenarios/DependentValidation",
};

const min = numberField({
name: "min",
schema: z.number().min(0),
});

const max = numberField({
name: "max",
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/54539
schema: (s, get) => {
const minVal = get(get(min).value);
return z.number().min(minVal ?? 0);
},
});

export const Range = formStory({
args: {
fields: {
min,
max,
},
children: ({ fields }) => (
<>
<NumberInput field={fields.min} label="Min" />
<NumberInput field={fields.max} label="Max" />
</>
),
},
});

const password = textField({
name: "password",
schema: z.string().min(6),
});

// TODO: custom error
const confirmPassword = textField({
name: "confirmPassword",
validate: zodValidate(
(get) => {
const initialPassword = get(get(password).value);
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/54539
schema: (s, get) => {
const initialPassword = get(get(password).value);

return z.literal(initialPassword);
},
{
on: "change",
formatError: ({ issues }) => {
return issues.map(({ code, message }) =>
code === "invalid_literal" ? "Passwords must match" : message,
);
},
},
),
return z.literal(initialPassword);
},
});

export const Primary = formStory({
export const PasswordValidation = formStory({
args: {
fields: {
password,
Expand Down
4 changes: 2 additions & 2 deletions src/scenarios/dependent-validation/Docs.mdx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Meta, Markdown, Stories } from "@storybook/blocks";
import * as PasswordValidation from "./PasswordValidation.stories";
import * as DependentValidation from "./DependentValidation.stories";

<Meta title="guides/DependentValidation" of={PasswordValidation} />
<Meta title="scenarios/DependentValidation" of={DependentValidation} />

# Dependend field validation

Expand Down

0 comments on commit c15d703

Please sign in to comment.