Home > Back-end >  Creating custom validator reactive form from regular expression angular
Creating custom validator reactive form from regular expression angular

Time:02-06

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

CodePudding user response:

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

CodePudding user response:

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}')]]
});

  •  Tags:  
  • Related