custom validator pattern with special characters Angular 4

chris_r picture chris_r · Jun 13, 2018 · Viewed 9.9k times · Source

I have a formgroup using custom validators:

return this.register = this.fb.group({
        username: ['', Validators.required, /* this.validateUsername()*/],
        email: ['', Validators.email, /*  this.validateUsername()*/],
        password: ['',
            [
                Validators.required,
                Validators.maxLength(50),
                Validators.minLength(8),
                Validators.pattern('^[a-zA-Z0-9!@#$%^&*()]+$'),
            ]
        ]
    });

I am trying to achieve validator pattern, but it doesn't work, someone help please.

Answer

Ulrich Dohou picture Ulrich Dohou · Jun 13, 2018

Make sure to add a / at start and the end of the regex string like this.

Validators.pattern(/^[a-zA-Z0-9!@#$%^&*()]+$/)