Security News
tea.xyz Spam Plagues npm and RubyGems Package Registries
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
remix-validated-form
Advanced tools
Readme
A form library built for Remix to make validation easy.
The docs are located a remix-validated-form.io.
https://user-images.githubusercontent.com/2811287/145734901-700a5085-a10b-4d89-88e1-5de9142b1e85.mov
To run sample-app
:
git clone https://github.com/airjp73/remix-validated-form
cd ./remix-validated-form
yarn install
yarn build
yarn sample-app
npm install remix-validated-form
There are official adapters available for zod
and yup
.
If you're using a different library, see the Validation library support section below.
npm install @remix-validated-form/with-zod
If you're using zod, you might also find zod-form-data
helpful.
In order to display field errors or do field-by-field validation, it's recommended to incorporate this library into an input component using useField
.
import { useField } from "remix-validated-form";
type MyInputProps = {
name: string;
label: string;
};
export const MyInput = ({ name, label }: MyInputProps) => {
const { error, getInputProps } = useField(name);
return (
<div>
<label htmlFor={name}>{label}</label>
<input {...getInputProps({ id: name })} />
{error && <span className="my-error-class">{error}</span>}
</div>
);
};
To best take advantage of the per-form submission detection, we can create a submit button component.
import { useFormContext, useIsSubmitting } from "remix-validated-form";
export const MySubmitButton = () => {
const isSubmitting = useIsSubmitting();
const { isValid } = useFormContext();
const disabled = isSubmitting || !isValid;
return (
<button
type="submit"
disabled={disabled}
className={disabled ? "disabled-btn" : "btn"}
>
{isSubmitting ? "Submitting..." : "Submit"}
</button>
);
};
Now that we have our components, making a form is easy.
import { DataFunctionArgs, json, redirect } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import * as yup from "yup";
import { validationError, ValidatedForm, withYup } from "remix-validated-form";
import { MyInput, MySubmitButton } from "~/components/Input";
// Using yup in this example, but you can use anything
const validator = withYup(
yup.object({
firstName: yup.string().label("First Name").required(),
lastName: yup.string().label("Last Name").required(),
email: yup.string().email().label("Email").required(),
})
);
export const action = async ({ request }: DataFunctionArgs) => {
const fieldValues = await validator.validate(await request.formData());
if (fieldValues.error) return validationError(fieldValues.error);
const { firstName, lastName, email } = fieldValues.data;
// Do something with correctly typed values;
return redirect("/");
};
export const loader = async (args: DataFunctionArgs) => {
return json({
defaultValues: {
firstName: "Jane",
lastName: "Doe",
email: "jane.doe@example.com",
},
});
};
export default function MyForm() {
const { defaultValues } = useLoaderData<typeof loader>();
return (
<ValidatedForm
validator={validator}
method="post"
defaultValues={defaultValues}
>
<MyInput name="firstName" label="First Name" />
<MyInput name="lastName" label="Last Name" />
<MyInput name="email" label="Email" />
<MySubmitButton />
</ValidatedForm>
);
}
You can use nested objects and arrays by using a period (.
) or brackets ([]
) for the field names.
export default function MyForm() {
const { defaultValues } = useLoaderData<typeof loader>();
return (
<ValidatedForm
validator={validator}
method="post"
defaultValues={defaultValues}
>
<MyInput name="firstName" label="First Name" />
<MyInput name="lastName" label="Last Name" />
<MyInput name="address.street" label="Street" />
<MyInput name="address.city" label="City" />
<MyInput name="phones[0].type" label="Phone 1 Type" />
<MyInput name="phones[0].number" label="Phone 1 Number" />
<MyInput name="phones[1].type" label="Phone 2 Type" />
<MyInput name="phones[1].number" label="Phone 2 Number" />
<MySubmitButton />
</ValidatedForm>
);
}
There are official adapters available for zod
and yup
, but you can easily support whatever library you want by creating your own adapter.
And if you create an adapter for a library, feel free to make a PR on this repository 😊
Any object that conforms to the Validator
type can be passed into the the ValidatedForm
's validator
prop.
type FieldErrors = Record<string, string>;
type ValidationResult<DataType> =
| { data: DataType; error: undefined }
| { error: FieldErrors; data: undefined };
type ValidateFieldResult = { error?: string };
type Validator<DataType> = {
validate: (unvalidatedData: unknown) => ValidationResult<DataType>;
validateField: (
unvalidatedData: unknown,
field: string
) => ValidateFieldResult;
};
In order to make an adapter for your validation library of choice, you can create a function that accepts a schema from the validation library and turns it into a validator.
Note the use of createValidator
.
It takes care of unflattening the data for nested objects and arrays since the form doesn't know anything about object and arrays and this should be handled by the adapter.
For more on this you can check the implementations for withZod
and withYup
.
The out-of-the-box support for yup
in this library works as the following:
export const withYup = <Schema extends AnyObjectSchema>(
validationSchema: Schema
// For best result with Typescript, we should type the `Validator` we return based on the provided schema
): Validator<InferType<Schema>> =>
createValidator({
validate: (unvalidatedData) => {
// Validate with yup and return the validated & typed data or the error
if (isValid) return { data: { field1: "someValue" }, error: undefined };
else return { error: { field1: "Some error!" }, data: undefined };
},
validateField: (unvalidatedData, field) => {
// Validate the specific field with yup
if (isValid) return { error: undefined };
else return { error: "Some error" };
},
});
remix-validated-form
ones?This is happening because you or the library you are using is passing the required
attribute to the fields.
This library doesn't take care of eliminating them and it's up to the user how they want to manage the validation errors.
If you wan't to disable all native HTML validations you can add noValidate
to <ValidatedForm>
.
We recommend this approach since the validation will still work even if JS is disabled.
Problem: how do we trigger a toast message on success if the action redirects away from the form route? The Remix solution is to flash a message in the session and pick this up in a loader function, probably in root.tsx See the Remix documentation for more information.
Problem: the cancel button has an onClick handler to navigate away from the form route but instead it is submitting the form.
A button defaults to type="submit"
in a form which will submit the form by default. If you want to prevent this you can add type="reset"
or type="button"
to the cancel button.
FAQs
Form component and utils for easy form validation in remix
The npm package remix-validated-form receives a total of 24,918 weekly downloads. As such, remix-validated-form popularity was classified as popular.
We found that remix-validated-form demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.
Security News
UnitedHealth Group disclosed that the ransomware attack on Change Healthcare compromised protected health information for millions in the U.S., with estimated costs to the company expected to reach $1 billion.