0

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

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:(

2
  • You can find the guide from the Angular Docs on how to do it here Commented Feb 5, 2022 at 18:17
  • I have updated the question, and tried but i dont have luck Commented Feb 5, 2022 at 18:38

2 Answers 2

1

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

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

Comments

0

If you are using reactive form, then you can put it directly when you are creating the form.

filterForm: FormGroup;

filterForm = formBuilder.group({
  firstName: [null],
  lastName: [null],
  zipCode: [null, [Validators.pattern('[0-9]{5}')]]
});

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.