Skip to content

Enhance all Validator Decorators with optional ValidationOptions object to support custom error messages #21

@waji-io

Description

@waji-io

Currently, the built-in validator decorators have hard-coded error messages. For example:

export function LowerOrEqual(max: number): PropertyDecorator {
	return createDecorator(
		(prop: number) => lowerOrEqual(prop, max),
		{
			errorMessage: `Number must be lower than or equal ${constraintKey}1`,
			constraints: [max],
		},
	);
}

But there might be use cases where users want to define their own error-messages, either in a different language or by providing additional information. Here is one possible solution with an example:

// By treating this an object, additional options could be added later, if needed. For now, this ValiatorOptionsType only covers "message".
export type ValidatorOptionType = {
    message?: string;
}

// Sample validator making use of it
export const IsNotEmpty = ({ message = 'Property must not be empty' }: ValidatorOptionType = {}): PropertyDecorator =>
  createDecorator(
    (prop: unknown) => prop !== '' && prop !== null && prop !== undefined,
    { errorMessage: message, constraints: [] }
  );

If user provides a message, this custom message will be used. Otherwise, the default message. In addition, the IDE even shows a preview of the default error message.

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions