zod-ff 中文文档教程

发布于 2年前 浏览 14 项目主页 更新于 2年前

Zod 友好表单

Deno版本Npmjs.org 版本GitHub 工作流程状态测试覆盖率NPM Downloads

返回包含 errorsvalidData 的对象。 错误对象 包含用户友好的错误消息,可以轻松显示验证 给用户带来的错误,而 validData 对象包含类型化且有效的数据 来自模式的数据。该库可以在任何框架中使用,无论是在 服务器或客户端,它允许轻松验证和处理表单 意见书。

安装 (npm)

pnpm add zod-ff zod

Deno

import { parseForm } from "https://deno.land/x/zod_ff";

使用

创建一个 zod 架构。

import { z } from "zod";
const schema = z.object({
  email: z.string().email(),
});

当您准备好验证输入数据时,请继续运行 parseForm 功能。如果有任何错误,可以通过输入键查看。

import { parseForm } from "zod-ff";

const data = {
  email: "invalid-email",
};
const { errors } = parseForm({ schema, data });

errors;
// {
//   email: "Invalid email",
// }

如果错误未定义,则输入有效。返回的 validData 对象将 与您的回复一起输入。

import { parseForm } from "zod-ff";

const data = {
  email: "bob@example.com",
};
const { errors, validData } = parseForm({ schema, data });

errors;
// undefined

validData;
// {
//   email: "bob@example.com",
// }
const schema = z.object({
  user: z.object({
    email: z.string().email(),
  }),
});

const data = {
  user: {
    email: "bob",
  },
};

const { errors } = parseForm({ schema: RegisterSchema, data }, options);

errors;
// {
//   "user.email": "Invalid Email Address",
// }

示例

该库可以在任何框架的服务器或客户端上运行。

Svelte 示例

<script lang="ts">
  import { z } from "zod";
  import { parseForm } from "zod-ff";

  import { handleLogin } from "./my-login-function";

  let errors;

  const LoginSchema = z.object({
    email: z.string().email(),  
    password: z.string().min(8),  
  });  

  const loginForm = {  
    email: "",  
    password: "",  
  };  

  async function submit() {  
    let { data, errors } = await parseForm<typeof LoginSchema>({ schema: LoginSchema, data: loginForm });  
    if (!errors) await handleLogin(data);  
  }  
</script>  

<form on:submit|preventDefault="{submit}">  
  <label for="email">Email
    {#if errors?.email}<span class="error">{errors.email}</span>{/if}
    <input
      id="email"
      name="email"
      type="email"
      required="required"
      bind:value="{loginForm.email}"
    />
  </label>

  <label for="password">Password
    {#if errors?.password}<span class="error">{errors.password}</span>{/if}
    <input
      id="password"
      name="password"
      type="password"
      required="required"
      bind:value="{loginForm.password}"
    />
  </label>

  <footer class="form-submit">  
    <button type="submit">Submit</button>  
  </footer>  
</form>

React 示例

import React, { useState } from "react";
import { z } from "zod";
import { parseForm } from "zod-ff";
import { handleLogin } from "./my-login-function";

const LoginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8),
  rememberMe: z.boolean(),
});

const LoginForm = () => {
  const [formData, setFormData] = useState({
    email: "",
    password: "",
    rememberMe: false,
  });
  const [errors, setErrors] = useState({});

  const handleSubmit = async (e) => {
    e.preventDefault();
    let { data, errors } = await parseForm({
      schema: LoginSchema,
      data: formData,
    });
    if (!errors) await handleLogin(data);
    setErrors(errors);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">
        Email
        {errors.email && <span className="error">{errors.email}</span>}
        <input
          id="email"
          name="email"
          type="email"
          required
          value={formData.email}
          onChange={(e) => setFormData({ ...formData, email: e.target.value })}
        />
      </label>

      <label htmlFor="password">
        Password
        {errors.password && <span className="error">{errors.password}</span>}
        <input
          id="password"
          name="password"
          type="password"
          required
          value={formData.password}
          onChange={(e) =>
            setFormData({ ...formData, password: e.target.value })}
        />
      </label>
      <label htmlFor="rememberMe">
        Remember Me
        <input
          id="rememberMe"
          type="checkbox"
          checked={formData.rememberMe}
          onChange={(e) =>
            setFormData({ ...formData, rememberMe: e.target.checked })}
        />
      </label>

      <footer className="form-submit">
        <button type="submit">Submit</button>
      </footer>
    </form>
  );
};

Vue 3 示例

<template>  
  <form @submit.prevent="submit">  
    <label for="email">Email
      <span class="error" v-if="errors.email">{{ errors.email }}</span>
      <input
        id="email"
        name="email"
        type="email"
        required
        v-model="formData.email"
      />
    </label>

    <label for="password">Password
      <span class="error" v-if="errors.password">{{ errors.password }}</span>
      <input
        id="password"
        name="password"
        type="password"
        required
        v-model="formData.password"
      />
    </label>
    <label for="rememberMe">Remember Me
      <input
        id="rememberMe"
        type="checkbox"
        v-model="formData.rememberMe"
      />
    </label>

    <footer class="form-submit">
      <button type="submit">Submit</button>  
    </footer>  
  </form>  
</template>

<script>
import { z } from 'zod';
import { parseForm } from 'zod-ff';
import { handleLogin } from './my-login-function';

const LoginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8),
  rememberMe: z.boolean(),  
});  

export default {  
  data() {  
    return {  
      formData: {  
        email: "",  
        password: "",  
        rememberMe: false,  
      },  
      errors: {}  
    };  
  },  
  methods: {  
    async submit() {  
      let { data, errors } = await parseForm({ schema: LoginSchema, data: this.formData });  
      if (!errors) await handleLogin(data);  
      this.errors = errors;  
    }  
  }  
};  
</script>

[deno-package]:https://deno.land/x/zod_ff [npm-package]:https://www.npmjs.com/package/zod-ff

Zod Friendly Forms

Deno VersionNpmjs.org VersionGitHub Workflow StatusTest CoverageNPM Downloads

Returns an object containing errors and validData. The errors object contains user-friendly error messages, making it easy to display validation errors to the user, while the validData object contains the typed and valid data from the schema. This library can be used in any framework, both on the server or client side and it allows for easy validation and handling of form submissions.

Install (npm)

pnpm add zod-ff zod

Deno

import { parseForm } from "https://deno.land/x/zod_ff";

Usage

Create a zod schema.

import { z } from "zod";
const schema = z.object({
  email: z.string().email(),
});

When you're ready to validate your input data, go ahead and run the parseForm function. If there are any errors, they will be available by input key.

import { parseForm } from "zod-ff";

const data = {
  email: "invalid-email",
};
const { errors } = parseForm({ schema, data });

errors;
// {
//   email: "Invalid email",
// }

If errors are undefined, the input was valid. A returned validData object will be typed with your response.

import { parseForm } from "zod-ff";

const data = {
  email: "bob@example.com",
};
const { errors, validData } = parseForm({ schema, data });

errors;
// undefined

validData;
// {
//   email: "bob@example.com",
// }
const schema = z.object({
  user: z.object({
    email: z.string().email(),
  }),
});

const data = {
  user: {
    email: "bob",
  },
};

const { errors } = parseForm({ schema: RegisterSchema, data }, options);

errors;
// {
//   "user.email": "Invalid Email Address",
// }

Examples

This library will work on the server or client, in any framework.

Svelte Examples

<script lang="ts">
  import { z } from "zod";
  import { parseForm } from "zod-ff";

  import { handleLogin } from "./my-login-function";

  let errors;

  const LoginSchema = z.object({
    email: z.string().email(),  
    password: z.string().min(8),  
  });  

  const loginForm = {  
    email: "",  
    password: "",  
  };  

  async function submit() {  
    let { data, errors } = await parseForm<typeof LoginSchema>({ schema: LoginSchema, data: loginForm });  
    if (!errors) await handleLogin(data);  
  }  
</script>  

<form on:submit|preventDefault="{submit}">  
  <label for="email">Email
    {#if errors?.email}<span class="error">{errors.email}</span>{/if}
    <input
      id="email"
      name="email"
      type="email"
      required="required"
      bind:value="{loginForm.email}"
    />
  </label>

  <label for="password">Password
    {#if errors?.password}<span class="error">{errors.password}</span>{/if}
    <input
      id="password"
      name="password"
      type="password"
      required="required"
      bind:value="{loginForm.password}"
    />
  </label>

  <footer class="form-submit">  
    <button type="submit">Submit</button>  
  </footer>  
</form>

React Example

import React, { useState } from "react";
import { z } from "zod";
import { parseForm } from "zod-ff";
import { handleLogin } from "./my-login-function";

const LoginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8),
  rememberMe: z.boolean(),
});

const LoginForm = () => {
  const [formData, setFormData] = useState({
    email: "",
    password: "",
    rememberMe: false,
  });
  const [errors, setErrors] = useState({});

  const handleSubmit = async (e) => {
    e.preventDefault();
    let { data, errors } = await parseForm({
      schema: LoginSchema,
      data: formData,
    });
    if (!errors) await handleLogin(data);
    setErrors(errors);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">
        Email
        {errors.email && <span className="error">{errors.email}</span>}
        <input
          id="email"
          name="email"
          type="email"
          required
          value={formData.email}
          onChange={(e) => setFormData({ ...formData, email: e.target.value })}
        />
      </label>

      <label htmlFor="password">
        Password
        {errors.password && <span className="error">{errors.password}</span>}
        <input
          id="password"
          name="password"
          type="password"
          required
          value={formData.password}
          onChange={(e) =>
            setFormData({ ...formData, password: e.target.value })}
        />
      </label>
      <label htmlFor="rememberMe">
        Remember Me
        <input
          id="rememberMe"
          type="checkbox"
          checked={formData.rememberMe}
          onChange={(e) =>
            setFormData({ ...formData, rememberMe: e.target.checked })}
        />
      </label>

      <footer className="form-submit">
        <button type="submit">Submit</button>
      </footer>
    </form>
  );
};

Vue 3 Example

<template>  
  <form @submit.prevent="submit">  
    <label for="email">Email
      <span class="error" v-if="errors.email">{{ errors.email }}</span>
      <input
        id="email"
        name="email"
        type="email"
        required
        v-model="formData.email"
      />
    </label>

    <label for="password">Password
      <span class="error" v-if="errors.password">{{ errors.password }}</span>
      <input
        id="password"
        name="password"
        type="password"
        required
        v-model="formData.password"
      />
    </label>
    <label for="rememberMe">Remember Me
      <input
        id="rememberMe"
        type="checkbox"
        v-model="formData.rememberMe"
      />
    </label>

    <footer class="form-submit">
      <button type="submit">Submit</button>  
    </footer>  
  </form>  
</template>

<script>
import { z } from 'zod';
import { parseForm } from 'zod-ff';
import { handleLogin } from './my-login-function';

const LoginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8),
  rememberMe: z.boolean(),  
});  

export default {  
  data() {  
    return {  
      formData: {  
        email: "",  
        password: "",  
        rememberMe: false,  
      },  
      errors: {}  
    };  
  },  
  methods: {  
    async submit() {  
      let { data, errors } = await parseForm({ schema: LoginSchema, data: this.formData });  
      if (!errors) await handleLogin(data);  
      this.errors = errors;  
    }  
  }  
};  
</script>

[deno-package]: https://deno.land/x/zod_ff [npm-package]: https://www.npmjs.com/package/zod-ff

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文