Adria
A super simple form validation library, with autocomplete and value/type checking using the power of TypeScript.
npm i adria-forms
Overview
import { Form } from "adria-forms";
const form = new Form().field("username", (value) => {
if (!value) return "Please enter your username";
if (value.length < 4) return "Username must be at least 4 characters long";
return;
});
const formData = new FormData();
const errors = await form.validate(formData);
const usernameError = errors?.username;
Reference
.field()
Creates a new field. fieldName
cannot be an existing field name, and validate
can be a synchronous or asynchronous function. A void
return from validate
will tell Adria the value has passed the validation.
const field: (
fieldName: string,
validate: (
value: null | FormDataEntryValue,
formData: Map<string, FormDataEntryValue | null>
) => MaybePromise<void | any>
) => this;
Example
new Form()
.field("username", (value) => {
if (!value)
return {
code: 0,
message: "empty input",
};
return;
})
.field("password", (_, formData) => {
const usernameField = formData.get("username");
const passwordField = formData.get("randomFieldName");
})
.field(
"username"
);
.validate()
Validates the form data. Will only check fields defined with .field()
. Will return null
if the form data is valid or a fieldName:errorMessage record if not.
const validate: (formData: FormData) => Promise<Record<string, any> | null>;
Example
const form = new Form()
.field("username", () => {
return "error";
})
.field("password", () => {
return {
code: 0,
};
});
const errors = await form.validate(formData as FormData);
const userNameError: "fail" = errors.username;
const randomError = errors.random;
const passwordErrorCode: number = errors.password.code;
TypeScript tips
In the previous example (validate()), errors will only be typed with a value when the validate function returns a string/number. We can fix this by typing the return value of the validate function as const
.
const form = new Form().field("password", () => {
return {
code: 0,
} as const;
});
const errors = await form.validate(formData as FormData);
const passwordErrorCode: number = errors.password.code;