Skip to content

Commit

Permalink
Add string.exactLength (#236)
Browse files Browse the repository at this point in the history
  • Loading branch information
bvego committed May 4, 2020
1 parent d4e2c50 commit efa17a0
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,16 @@ UserSchema.validate({
Nope.string()
.lessThan(4)
.validate('http'); // returns the error message

- `exactLength(length: number, message: string)` - Asserts if the entry is of exact length
- ```js
Nope.string()
.exactLength(4)
.validate('test'); // returns undefined
Nope.string()
.exactLength(4)
.validate('testing'); // returns the error message
```

- `Number`
Expand Down
4 changes: 4 additions & 0 deletions src/NopePrimitive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ abstract class NopePrimitive<T> implements Validatable<T> {

public oneOf(options: (T | NopeReference | Nil)[], message = 'Invalid option') {
const rule: Rule<T> = (entry, context) => {
if (entry === undefined) {
return;
}

const resolvedOptions = options.map((option) => resolveNopeRef(option, context));

if (resolvedOptions.indexOf(entry) === -1) {
Expand Down
15 changes: 15 additions & 0 deletions src/NopeString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,21 @@ class NopeString extends NopePrimitive<string> {

return this.test(rule);
}

public exactLength(length: number, message = `Must be at exactly of length ${length}`) {
const rule: Rule<string> = (entry) => {
if (this.isEmpty(entry)) {
return;
}

const value = entry as string;
if (value.length !== length) {
return message;
}
};

return this.test(rule);
}
}

export default NopeString;
9 changes: 9 additions & 0 deletions src/__tests__/NopeString.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,4 +186,13 @@ describe('#NopeString', () => {
expect(Nope.string().required('requiredMessage').validate(' ')).toBe('requiredMessage');
});
});

describe('#exactLength', () => {
it('should return work', () => {
expect(Nope.string().exactLength(5, 'msg').validate(undefined)).toBe(undefined);
expect(Nope.string().exactLength(5, 'msg').validate('123')).toBe('msg');
expect(Nope.string().exactLength(5, 'msg').validate('123456')).toBe('msg');
expect(Nope.string().exactLength(5, 'msg').validate('lucky')).toBe(undefined);
});
});
});

0 comments on commit efa17a0

Please sign in to comment.