Form validation with class-validator

import { validateOrReject, Length, IsEmail, IsString} from "class-validator";
import type { ValidationError } from "class-validator";

// validation
export class LoginValidation {
  email!: string | null;

  @Length(8, 16)
  password!: string | null;

export async function validateInput (input: LoginValidation) {
  try {
    await validateOrReject(input);
    return { errors: {} };
  } catch (err) {
    console.warn("[Validations] error");
    const validationErrors = err as ValidationError[];
    const errorsList: Record<string, string> = validationErrors.reduce(
    (prevError, currError) => {
      const property =;
      const message = Object.values(currError.constraints!)[0];
      return {...prevError, [property]: message };
    return { errors: errorsList };

const validation = new LoginValidation(); = "email"

const validate = await validateInput(validation);
//{errors: {email: "email must be a valid email"}}

Easy way to use class-validator to validate your forms.

BETA Snippet explanation automatically generated by OpenAI:

Here is what the above code is doing:
1. We are creating a class called LoginValidation and it has a couple of properties (email and password)
2. We are creating a function that takes a LoginValidation object and returns a promise
3. We are creating a try/catch block that validates the input and returns

Snippet By ArmahLance


Created June 13th, 2022


Report Snippet