fabian-hiller / modular-forms

The modular and type-safe form library for SolidJS, Qwik and Preact
https://modularforms.dev
MIT License
966 stars 49 forks source link

Are there any plans to add type validation to the "Typebox" library? #127

Open rhkdgns95 opened 12 months ago

rhkdgns95 commented 12 months ago

Issue

Hello.

These days, I am very interested in qwik, so I configure the screen with the framework and develop it through a separate bun (elysia framework).

Currently, the repository manages the front/backend through turborepo. (This environment configuration has disadvantages, but it has the strength of type inference)

my workspace

Please inquire about the following. Previously, the server side configured schema verification for development through typebox, not zod.

However, qwik currently provides only the verification libraries zod and vali. Therefore, I worked by customizing the validation for typebox. When I configured the following code, it was verified normally (both client / backend)

Is adding typebox as qwik's verification type a limitation?

//typeboxForm$.ts

import { $, implicit$FirstArg } from "@builder.io/qwik";
import { TSchema, type Static, Type } from "@sinclair/typebox";
import { FieldValues, MaybeFunction, ValidateForm } from "@modular-forms/qwik";
import { type QRL } from "@builder.io/qwik";
import { Value } from "@sinclair/typebox/value";

/**
 * Parses a value with a Typebox schema and returns the result.
 *
 * @param schema The Typebox schema.
 * @param value The value.
 *
 * @returns The parse result.
 */
async function getParsedTypeboxSchema(
  schema: QRL<MaybeFunction<Static<TSchema>>>,
  value: FieldValues
) {
  const typeboxSchema = await schema.resolve();
  return Value.Errors(
    typeof typeboxSchema === "function" ? typeboxSchema() : typeboxSchema,
    value
  );
}

/**
 * See {@link typeboxForm$}
 */
export function typeboxFormQrl(schema: QRL<MaybeFunction<Static<TSchema>>>) {
  return $(async (values: FieldValues) => {
    const result = await getParsedTypeboxSchema(schema, values);

    if (result) {
      const resultErrors = result.First();

      console.log({ resultErrors });
      if (resultErrors?.path) {
        const path = resultErrors.path.replace(/\//, "");
        return {
          [path]: resultErrors?.schema?.error || resultErrors?.message,
        };
      }
    }
    return {};
  });
}
/**
 * Creates a validation functions that parses the Typebox schema of a form.
 *
 * @param schema A Typebox schema.
 *
 * @returns A validation function.
 */

export const typeboxForm$ = implicit$FirstArg(typeboxFormQrl);
fabian-hiller commented 12 months ago

I am open to add more adapters to Modular Forms. You are welcome to create a PR for typeboxForm$ and typeboxField$. To avoid adding @sinclair/typebox as a dependency, we should investigate the use of dynamic imports.