2

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.

1
  • Can you not use @ArrayContains(values: any[])? Commented Oct 21, 2021 at 8:45

1 Answer 1

0

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

Playground

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.