10.0.1 โ€ข Published 8 months ago

@hodfords/nestjs-validation v10.0.1

Weekly downloads
-
License
ISC
Repository
github
Last release
8 months ago

Installation ๐Ÿค–

Install the nestjs-validation package with:

npm install @hodfords/nestjs-validation --save

Usage ๐Ÿš€

First, create an instance of ValidationPipe with the desired configuration:

import { ValidationPipe } from '@hodfords/nestjs-validation';
import { ValidateException } from '@hodfords/nestjs-exception';

export const validateConfig = new ValidationPipe({
    whitelist: true,
    stopAtFirstError: true,
    forbidUnknownValues: false,
    exceptionFactory: (errors): ValidateException => new ValidateException(errors)
});

Next, set the validation configuration globally in your bootstrap function:

async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    app.useGlobalPipes(validateConfig);
    await app.listen(3000);
}

Customize Validation Error

The original error message provides basic information but lacks detail. With nestjs-validation, you can enhance these errors by adding meaningful context, such as the fieldโ€™s property name, value, and target object.

Original Validation Error

ValidationError {
  target: AppDto { stringValue: undefined },
  value: undefined,
  property: 'stringValue',
  children: [],
  constraints: { isString: 'stringValue must be a string' }
}

Customized Validation Error

ValidationError {
  target: AppDto { stringValue: undefined },
  value: undefined,
  property: 'stringValue',
  children: [],
  constraints: {
    isString: {
      message: '$property must be a string',
      detail: { property: 'stringValue', target: 'AppDto', value: undefined }
    }
  }
}

Exception

When combined with nestjs-exception, errors are translated into localized messages:

{
    "message": "Validate Exception",
    "errors": {
        "stringValue": {
            "messages": ["String Value must be a string"]
        }
    }
}

License ๐Ÿ“

This project is licensed under the MIT License

10.0.1

8 months ago

10.0.0

9 months ago

1.0.0-rc.1

9 months ago