npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

zod-ff

v1.4.0

Published

Zod Friendly Forms. Form validation for humans.

Downloads

749

Readme

Zod Friendly Forms

Deno Version Npmjs.org Version GitHub Workflow Status Test Coverage NPM 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: "[email protected]",
};
const { errors, validData } = parseForm({ schema, data });

errors;
// undefined

validData;
// {
//   email: "[email protected]",
// }

You can use the builtin FormData or URLSearchParams object.

const data = new FormData();
data.append("email", "invalid-email");

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

errors;
// {
//   email: "Invalid email",
// }
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>