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

Support for custom validators #164

Merged
merged 5 commits into from
Aug 19, 2018

Conversation

vnenkpet
Copy link
Contributor

@vnenkpet vnenkpet commented Jun 24, 2018

Adds support for custom validators. Sync/async functions or regex.

Example (added to README.md):

// 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;

@coveralls
Copy link

coveralls commented Jun 24, 2018

Coverage Status

Coverage remained the same at 87.009% when pulling 6b524ce on vnenkpet:pr-custom-validators into 24b66fd on szokodiakos:master.

@vnenkpet
Copy link
Contributor Author

I'm not sure how much is this repo maintained but it would be nice to have this feature as it's a default mongoose feature that is missing for a reason I don't understand.

All I did could be also achieved by simply adding validate?: any to the BasePropOptions interface in src/prop.ts. I just added some type checking and updated README on top of that, also included one use case in tests.

I'm already using this in my projects and it works without a problem so far.

@Ben305 Ben305 merged commit 7d5a021 into szokodiakos:master Aug 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants