Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the ability to provide custom messages #177

Merged
merged 6 commits into from
Sep 30, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,42 @@ ow(1, 'input', ow.number.validate(value => ({
//=> ArgumentError: Expected number `input` to be greater than 10, got 1
```

#### message(string | fn)

Provide a custom message:

```ts
ow('🌈', 'unicorn', ow.string.equals('🦄').message('Expected unicorn, got rainbow'));
//=> ArgumentError: Expected unicorn, got rainbow
```

You can also pass in a function which receives the value as the first parameter and the label as the second parameter and is expected to return the message.

```ts
ow('🌈', ow.string.minLength(5).message((value, label) => `Expected ${label}, to have a minimum length of 5, got \`${value}\``));
//=> ArgumentError: Expected string, to be have a minimum length of 5, got `🌈`
```

It's also possible to add a separate message per validation:

```ts
ow(
'1234',
ow.string
.minLength(5).message((value, label) => `Expected ${label}, to be have a minimum length of 5, got \`${value}\``)
.url.message('This is no url')
);
//=> ArgumentError: Expected string, to be have a minimum length of 5, got `1234`

ow(
'12345',
ow.string
.minLength(5).message((value, label) => `Expected ${label}, to be have a minimum length of 5, got \`${value}\``)
.url.message('This is no url')
);
//=> ArgumentError: This is no url
```
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The readme and TS doc comments should be in sync as much as possible. These examples are missing from the TS doc comments.

Copy link
Contributor Author

@GentileFulvio GentileFulvio Jun 6, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added two examples to the message function in source/predicates/predicate.ts. Would you like me to add all of the examples above ?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, if they are in the readme, they should go in index.d.ts.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also make sure the formatting is the same. It's not now.


This can be useful for creating your own reusable validators which can be extracted to a separate npm package.

## Maintainers
Expand All @@ -247,4 +283,3 @@ This can be useful for creating your own reusable validators which can be extrac

- [@sindresorhus/is](https://github.com/sindresorhus/is) - Type check values
- [ngx-ow](https://github.com/SamVerschueren/ngx-ow) - Angular form validation on steroids

24 changes: 24 additions & 0 deletions source/predicates/predicate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import {not} from '../operators/not';
import {BasePredicate, testSymbol} from './base-predicate';
import {Main} from '..';

/**
@hidden
*/
GentileFulvio marked this conversation as resolved.
Show resolved Hide resolved
export type ValidatorMessage<T> = (value: T, label?: string) => string;
sindresorhus marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not a validator message though, it creates the validator message. I think the name here could be improved.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed it to ValidatorMessageBuilder, couldn't really think on anything better. Any suggestions perhaps ?


/**
@hidden
*/
Expand Down Expand Up @@ -164,6 +169,25 @@ export class Predicate<T = unknown> implements BasePredicate<T> {
});
}

/**
Provide an new error message to be thrown when the validation fails.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed


@param newMessage - Either a string containing the new message or a function returning the new message
GentileFulvio marked this conversation as resolved.
Show resolved Hide resolved
*/
message(newMessage: string | ValidatorMessage<T>) {
const {validators} = this.context;

validators[validators.length - 1].message = (value, label) => {
if (typeof newMessage === 'function') {
return newMessage(value, label);
}

return newMessage;
};

return this;
}

/**
Register a new validator.

Expand Down
37 changes: 37 additions & 0 deletions test/custom-message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import test from 'ava';
import {default as ow, Predicate} from '../source';

class CustomPredicate extends Predicate<any> {
constructor() {
super('string');
}

get unicorn() {
return this.addValidator({
message: (value, label) => `Expected ${label} to be \`🦄\`, got \`${value}\``,
validator: value => value === '🦄'
});
}
}

test('custom validate message', t => {
t.throws(() => {
ow('🌈', 'unicorn', new CustomPredicate().unicorn.message('Expect unicorn, got rainbow'));
}, 'Expect unicorn, got rainbow');

t.throws(() => {
ow('🌈', 'unicorn', new CustomPredicate().unicorn.message((value, label) => `Expected ${label}, to be \`🦄\` got \`${value}\``));
}, 'Expected string `unicorn`, to be `🦄` got `🌈`');

t.throws(() => {
ow('🌈', ow.string.minLength(5).message((value, label) => `Expected ${label}, to be have a minimum length of 5, got \`${value}\``));
}, 'Expected string, to be have a minimum length of 5, got `🌈`');

t.throws(() => {
ow('1234', ow.string.minLength(5).message((value, label) => `Expected ${label}, to be have a minimum length of 5, got \`${value}\``).url.message('This is no url'));
}, 'Expected string, to be have a minimum length of 5, got `1234`');

t.throws(() => {
ow('12345', ow.string.minLength(5).message((value, label) => `Expected ${label}, to be have a minimum length of 5, got \`${value}\``).url.message('This is no url'));
}, 'This is no url');
});