Home > front end >  Angular Validator.pattern() does not give same results as online regex engines
Angular Validator.pattern() does not give same results as online regex engines

Time:11-25

I have a form group. And a regular expression to validate name. The constraints for the name input field are

  • required.
  • is alphanumeric.
  • starts with alphabets.
  • does not contain any special characters.

My regex(^[a-zA-Z][a-zA-Z0-9]*$) is working fine when checking online. regex-checking with regex101.com But with angular the formControl is showing valid for all strings.

Can anyone explain why is there such discrepancies between the results with angular Validator.pattern() and js engine.

I have tried the following with no avail (all are suggestions from stackoverflow answers):

  • Validators.pattern(/^[a-zA-Z][a-zA-Z0-9]*$/)
  • Validators.pattern('[a-zA-Z][a-zA-Z0-9]*')
const nameRegex='^[a-zA-Z][a-zA-Z0-9]*$'
this.signupForm = this.formBuilder.group({
      name: ['', Validators.required, Validators.pattern(nameRegex)],
      email: ['', [Validators.required, Validators.pattern(emailRegex)]],
      password: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
      c_password: ['', Validators.compose([Validators.required, Validators.minLength(6)])]

CodePudding user response:

You made a mistake in the FormGroup. The name form control validators is missing brackets.

name: ['', [Validators.required, Validators.pattern(nameRegex)]],
  • Related