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

@conform-to/validitystate

v0.2.0

Published

Validate on the server using the same rules as the browser

Downloads

111

Readme

@conform-to/validitystate

The current version is not compatible with conform react adapter.

Conform helpers for server validation based on the validation attributes.

API Reference

parse

A function to parse FormData or URLSearchParams on the server based on the constraints and an optional error formatter.

import { type FormConstraints, type FormatErrorArgs, parse } from '@conform-to/validitystate';

const constraints = {
    email: { type: 'email', required: true },
    password: { type: 'password', required: true },
    remember: { type: 'checkbox' },
} satisify FormConstraints;

function formatError({ input }: FormatErrorArgs) {
    switch (input.name) {
        case 'email': {
            if (input.validity.valueMissing) {
                return 'Email is required';
            } else if (input.validity.typeMismatch) {
                return 'Email is invalid';
            }
            break;
        }
        case 'password': {
            if (input.validity.valueMissing) {
                return 'Password is required';
            }
            break;
        }
     }

     return '';
}

const submission = parse(formData, {
  constraints,
  formatError,
});

// The error will be a dictinioary mapping input name to the corresponding errors
// e.g. { email: 'Email is required', password: 'Password is required' }
console.log(submission.error);

if (!submission.error) {
    // If no error, the parsed data will be available with the inferred type.
    // e.g. { email: string; password: string; remember: boolean; }
    console.log(submission.value);
}

The error formatter can also return multiple error.

function formatError({ input }: FormatErrorArgs) {
  const error = [];

  switch (input.name) {
    case 'email': {
      if (input.validity.valueMissing) {
        error.push('Email is required');
      }
      if (input.validity.typeMismatch) {
        error.push('Email is invalid');
      }
      break;
    }
    case 'password': {
      if (input.validity.valueMissing) {
        error.push('Password is required');
      }
      if (input.validity.tooShort) {
        error.push('Passowrd is too short');
      }
      break;
    }
  }

  return error;
}

If no error formatter is provided, check the defaultFormatError helpers for the default behavior.

validate

A helper to customize client validation by reusing the constraints and error formatter. Error will be set on the form control element using the setCustomValidity method. It should be called before reporting new error (i.e. triggering form.reportValidity()).

import { validate } from '@conform-to/validitystate';

function Example() {
  return (
    <form
      onSubmit={(event) => {
        const form = event.currentTarget;

        // validate before reporting new error
        validate(form, {
          constraints,
          formatError,
        });

        if (!form.reportValidity()) {
          event.preventDefault();
        }
      }}
      noValidate
    >
      {/* ... */}
    </form>
  );
}

defaultFormatError

This is the default error formatter used by parse to represent error by all failed validation attributes. For example:

{ "email": ["required", "type"], "password": ["required"] }

This helper is useful if you want to customize the error based on the default error formatter.

import { type FormConstraints, type FormatErrorArgs, defaultFormatError } from '@conform-to/validitystate';

const constraints = {
    email: { type: 'email', required: true },
    password: { type: 'password', required: true },
    confirmPassowrd: { type: 'password', required: true },
} satisify FormConstraints;

function formatError({ input }: FormatErrorArgs<typeof constraints>) {
    const error = defaultFormatError({ input });

    if (input.name === 'confirmPassword' && error.length === 0 && value.password !== value.confirmPassword) {
        error.push('notmatch');
    }

    return error;
}

const submission = parse(formData, {
    constraints,
    formatError,
});

getError

It gets the actual error messages stored on the validationMessage property. This is needed if the custom error formatter returns multiple error.

import { getError } from '@conform-to/validitystate';

function Example() {
  const [error, setError] = useState({});

  return (
    <form
      onInvalid={(event) => {
        const input = event.target as HTMLInputElement;

        setError((prev) => ({
          ...prev,
          [input.name]: getError(input.validationMessage),
        }));

        event.preventDefault();
      }}
    >
      {/* ... */}
    </form>
  );
}

Attributes supported

month and week input type are not implemented due to limited browser support

| Support | type | required | minLength | maxLength | pattern | min | max | step | multiple | | :------------- | :--: | :------: | :-------: | :-------: | :-----: | :-: | :-: | :--: | :------: | | text | | 🗸 | 🗸 | 🗸 | 🗸 | | | | | | email | 🗸 | 🗸 | 🗸 | 🗸 | 🗸 | | | | | | password | | 🗸 | 🗸 | 🗸 | 🗸 | | | | | | url | 🗸 | 🗸 | 🗸 | 🗸 | 🗸 | | | | | | tel | | 🗸 | 🗸 | 🗸 | 🗸 | | | | | | search | | 🗸 | 🗸 | 🗸 | 🗸 | | | | | | datetime-local | | 🗸 | | | | 🗸 | 🗸 | 🗸 | | | date | | 🗸 | | | | 🗸 | 🗸 | 🗸 | | | time | | 🗸 | | | | 🗸 | 🗸 | 🗸 | | | select | | 🗸 | | | | | | | 🗸 | | textarea | | 🗸 | 🗸 | 🗸 | | | | | | | radio | | 🗸 | | | | | | | | | color | | 🗸 | | | | | | | | | checkbox | | 🗸 | | | | | | | | | number | | 🗸 | | | | 🗸 | 🗸 | 🗸 | | | range | | 🗸 | | | | 🗸 | 🗸 | 🗸 | | | file | | 🗸 | | | | | | | 🗸 |