Skip to content
This repository has been archived by the owner on Jun 29, 2021. It is now read-only.

Commit

Permalink
Support for custom validators (#164)
Browse files Browse the repository at this point in the history
Support for custom validators
  • Loading branch information
vnenkpet authored and Ben305 committed Aug 19, 2018
1 parent 037098d commit 7d5a021
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 1 deletion.
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,50 @@ age?: number;
favouriteHexNumber: string;
```


- `validate` (custom validators): You can define your own validator function/regex using this. The function has to return a `boolean` or a Promise (async validation).

```typescript
// you have to get your own `isEmail` function, this is a placeholder

@prop({ validate: (value) => isEmail(value)})
email?: string;

// or

@prop({ validate: (value) => { return new Promise(res => { res(isEmail(value)) }) })
email?: string;

// or

@prop({ validate: {
validator: val => isEmail(val),
message: `{VALUE} is not a valid email`
}})
email?: string;

// or

@prop({ validate: /\S+@\S+\.\S+/ })
email?: string;

// you can also use multiple validators in an array.

@prop({ validate:
[
{
validator: val => isEmail(val),
message: `{VALUE} is not a valid email`
},
{
validator: val => isBlacklisted(val),
message: `{VALUE} is blacklisted`
}
]
})
email?: string;
```
Mongoose gives developers the option to create [virtual properties](http://mongoosejs.com/docs/api.html#schema_Schema-virtual). This means that actual database read/write will not occur these are just 'calculated properties'. A virtual property can have a setter and a getter. TypeScript also has a similar feature which Typegoose uses for virtual property definitions (using the `prop` decorator).
```typescript
Expand Down
7 changes: 7 additions & 0 deletions src/prop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,17 @@ export type Func = (...args: any[]) => any;

export type RequiredType = boolean | [boolean, string] | string | Func | [Func, string];

export type ValidatorFunction = (value: any) => boolean | Promise<boolean>;
export type Validator = ValidatorFunction | RegExp | {
validator: ValidatorFunction,
message?: string,
};

export interface BasePropOptions {
required?: RequiredType;
enum?: string[] | object;
default?: any;
validate?: Validator | Validator[];
unique?: boolean;
index?: boolean;
sparse?: boolean;
Expand Down
11 changes: 11 additions & 0 deletions src/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,4 +264,15 @@ describe('getClassForDocument()', () => {
expect(foundCar.price).to.be.a.instanceof(mongoose.Types.Decimal128);
expect(foundCar.price.toString()).to.eq('123.45');
});

it('Should validate email', async () => {
try {
await Person.create({
email: 'email',
});
fail('Validation must fail.');
} catch (e) {
expect(e).to.be.a.instanceof((mongoose.Error as any).ValidationError);
}
});
});
2 changes: 1 addition & 1 deletion src/test/models/person.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export abstract class PersistentModel extends tg.Typegoose {

export class Person extends PersistentModel {
// add new property
@tg.prop({ required: true })
@tg.prop({ required: true, validate: /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/ })
email: string;

// override instanceMethod
Expand Down

0 comments on commit 7d5a021

Please sign in to comment.