I have been using the class-validator decorator library to validate dto objects and would like to create a domain whitelist for the @IsEmail decorator. The library includes a @Contains decorator, which can be used for a single string (seed), but I would like to input an array of valid strings instead. Is this possible?
current
@Contains('@mydomain.com')
@IsEmail()
public email: string;
desired
@Contains(['@mydomain, @yourdomain, @wealldomain, @fordomain'])
@IsEmail()
public email: string;
If this is not possible, I would appreciate any direction on how to implement a custom decorator which serves this purpose.
Thanks.
COnsider this example:
const Contains = <Domain extends `@${string}`, Domains extends Domain[]>(domains: [...Domains]) =>
(target: Object, propertyKey: string) => {
let value: string;
const getter = () => value
const setter = function (newVal: Domain) {
if (domains.includes(newVal)) {
value = newVal;
}
else {
throw Error(`Domain should be one of ${domains.join()}`)
}
};
Object.defineProperty(target, propertyKey, {
get: getter,
set: setter
});
}
class Greeter {
@Contains(['@mydomain', '@wealldomain'])
greeting: string;
constructor(message: string) {
this.greeting = message;
}
}
const ok = new Greeter('@mydomain'); // ok
const error = new Greeter('234'); // runtime error
If you provide invalid email domain it will trigger runtime error. It is up to you how you want to implement validation logic. It might be not necessary a runtime error