Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating custom validator reactive form from regular expression angular

I have some regular expression validation that I use on email form, this is how it looks

this.customerForm = this.fb.group({
      email: [null, {
        Validators.pattern('^[^\\s@]+@[^\\s@]+\\.[^\\s@]{1,}$')],updateOn: 'blur'
      }]
    });

Validation work fine, but what i need is to make custom validator for this regular expression, any idea how to start, thanks

I have tried like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

properEmailValidator(): ValidatorFn {
    const nameRe = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{1,}$/;
    return (control: AbstractControl): ValidationErrors | null => {
      const forbidden = nameRe.test(control.value);
      return forbidden ? { emailNotValid: { value: control.value } } : null;
    };
  }

But this does not work:(

>Solution :

When you define the expresion as a string, you have to escape the backslashes, as you properly did in the Validators.pattern('^[^\\s@]+@[^\\s@]+\\.[^\\s@]{1,}$').

But if you define the expresión as a proper RegExp as you are doing in the validator function, you must not do it, as it would try to match it as a backslash character. So you need to modify your RegExp as follows.

const nameRe = /^[^\s@]+@[^\s@]+\.[^\s@]{1,}$/;

Cheers

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading