Form validation with class-validator
import { validateOrReject, Length, IsEmail, IsString} from "class-validator";
import type { ValidationError } from "class-validator";
// validation
export class LoginValidation {
@IsEmail()
email!: string | null;
@IsString()
@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 = currError.property;
const message = Object.values(currError.constraints!)[0];
return {...prevError, [property]: message };
},{});
return { errors: errorsList };
}
}
//example
const validation = new LoginValidation();
validation.email = "email"
validation.password="some+difficult-password"
const validate = await validateInput(validation);
//{errors: {email: "email must be a valid email"}}
Easy way to use class-validator to validate your forms.
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