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-messages

v1.0.6

Published

Zod error result messages to validation readable object

Downloads

6

Readme

Zod Messages

Zod Messages is a TypeScript project that provides a set of utilities for handling validation messages using the Zod library. This library allows you to easily validate your data and display error messages in a readable form within your components.

Features

  • Easy Integration: Seamlessly integrates with the Zod validation library.
  • Readable Messages: Transforms Zod error results into user-friendly validation messages.
  • TypeScript Support: Fully typed and compatible with TypeScript.
  • Flexible: Can be used in various JavaScript frameworks and environments.

Installation

Use the package manager npm to install Zod Messages.

npm install zod-messages

Usage with hooks

import { useValidator } from 'zod-messages';

// your code here

Simple Example useValidator

// model.ts
export interface User {
  name: string;
  email: string;
  age: number;
  address : {
    street: string;
    city: string;
  }
}
// schema.ts
import { z } from 'zod';


export const UserValidationSchema = z.object({
    name: z.string().min(3),
    email: z.string().email({ message: 'Invalid email address' }),
    age: z.number().min(15, { message: 'Age must be at least 15' }),
    address: addressSchema,
});

export const AddressValidationSchema = z.object({
    street: z.string().min(3),
    city: z.string().min(3),
});
// index.tsx

import { useValidator } from 'zod-messages';
import { ErrorMessage } from '@your-components/errorMessage/index';

export const YourComponent = () => {

    const { validate, validationMessages } = useValidator<User>(UserValidationSchema);

    const handleSubmit = (data: User) => {
        const result = validate(data);
        if (result.success) {
            // do something
        }
    }
    
    return (
        <form onSubmit={handleSubmit}>
            <input type="text" name="name" />
            <ErrorMessage message={validationMessages.name} />
            
            <input type="text" name="email" />
            <ErrorMessage message={validationMessages.email} />

            <input type="number" name="age" />
            <ErrorMessage message={validationMessages.age} /> //Age must be at least 15
            
            <input type="text" name="address.street" />
            <ErrorMessage message={validationMessages.address.street} />
            
            <input type="text" name="address.city" />
            <ErrorMessage message={validationMessages.address.city} />
            
            <button type="submit">Submit</button>
        </form>
    );
}

Example for use formatErrorMessages

//validation.ts

import { ValidationResult } from "./useValidator";

export const isUserValid = <T extends User>(data?: T): ValidationResult<T> => {
    const result = UserValidationSchema.safeParse(data ?? initUserData);

    return {
        isInvalid: !result.success,
        validationMessages: result.success ? {} : formatErrorMessages<T>(result.error),
    }
};

//result
// {
//     isInvalid: true,
//     validationMessages: {
//         name: 'Name is required',
//         email: 'Invalid email address',
//         age: 'Age must be at least 15',
//         address: {
//             street: 'Street is required',
//             city: undefined
//         }
//     }
// }

Advanced example - use custom error messages

import { z } from 'zod';


export const UserValidationSchema = z.object({
    name: z.string().min(3),
    email: z.string().email({ message: 'Invalid email address' }),
    address: addressSchema,
})
    .superRefine((data, ctx) => {
    if (data.address.city === 'New York') {
        return ctx.addIssue({
            code: z.ZodIssueCode.custom,
            path: ['address', 'city'],
            message: 'City cannot be New York',
        });
    }
})

or for use global error message

import {z} from 'zod';
import {eGlobalErrorMessage} from "./useValidator";


export const UserValidationSchema = z.object({
    name: z.string().min(3),
    email: z.string().email({message: 'Invalid email address'}),
})
    .superRefine((data, ctx) => {
    const diacritics = /[\u0300-\u036f]/g;
    
    if (diacritics.test(data.name)) {
        return ctx.addIssue({
            code: z.ZodIssueCode.custom,
            path: [eGlobalErrorMessage.globalErrorMessage],
            message: 'Name cannot contain diacritics',
        });
    }
})
// index.tsx
//...
return (
    <form onSubmit={handleSubmit}>
        <input type="text" name="name" />
        <ErrorMessage message={validationMessages.name ?? validationMessages.globalErrorMessage} />
    </form>);
//...

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

This project is licensed under the ISC License - see the LICENSE file for details.