Skip to content

Commit

Permalink
Add string.nonBlank (#227)
Browse files Browse the repository at this point in the history
  • Loading branch information
leaumar authored Nov 15, 2021
1 parent aa5ed44 commit 96207f0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
21 changes: 21 additions & 0 deletions source/predicates/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,27 @@ export class StringPredicate extends Predicate<string> {
});
}

/**
Test a string to contain at least 1 non-whitespace character.
*/
get nonBlank(): this {
return this.addValidator({
message: (value, label) => {
// Unicode's formal substitute characters can be barely legible and may not be easily recognized.
// Hence this alternative substitution scheme.
const madeVisible = value
.replace(/ /g, '·')
.replace(/\f/g, '\\f')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/\v/g, '\\v');
return `Expected ${label} to not be only whitespace, got \`${madeVisible}\``;
},
validator: value => value.trim() !== '',
});
}

/**
Test a string to be not empty.
*/
Expand Down
10 changes: 10 additions & 0 deletions test/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,16 @@ test('string.empty', t => {
}, {message: 'Expected string to be empty, got `foo`'});
});

test('string.nonBlank', t => {
t.notThrows(() => {
ow('foo', ow.string.nonBlank);
});

t.throws(() => {
ow(' \n\t\f\v', ow.string.nonBlank);
}, {message: 'Expected string to not be only whitespace, got `·\\n\\t\\f\\v`'});
});

test('string.nonEmpty', t => {
t.notThrows(() => {
ow('foo', ow.string.nonEmpty);
Expand Down

0 comments on commit 96207f0

Please sign in to comment.