angularangular6angular-reactive-formsangular-validationangular-validator

Angular 6 reactive form password validation regex pattern and confirmation validation


I am trying to build a registration form using Angular 6 reactive forms.

 ngOnInit() {
this.registerForm = this.formBuilder.group({
  firstName: ['', [Validators.required],
  lastName: ['', [Validators.required]],
  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.pattern('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&].{8,}$')]],
  confirmPassword: ['', [Validators.required, Validators.pattern('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&].{8,}$')]]
});

}

How can I make the validation so that will allow:

This regex I am using works fine but I cannot use any other special characters for example I tried Demoo123# and didn't work. However Demoo123@ worked fine. I assume there is a problem in my regex with the special characters section. Do I have to manually mention all allowed special characters? Or is there some kind of shortcut for that? I read somewhere that regex don't like hashtags #... is that true?

Another issue is how can I make a confirm validation so that the confirmPassword value must be same as password field value?


Solution

  • The problem was that I didn't add to the password field the pattern attribute. <input pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&].{8,}$" >

    That's quite wired. Why I need to specify it on the input when it is specified in the code? No idea but it works.