Search code examples
angularvalidationpasswords

Angular 15 Password Validation - prevent form submit until all conditions are true


I'm currently self-learning Angular (started with version 15), following watching a YouTube tutorial on creating a registration and login system. All works fine with that, but I now want to make some changes and I'm unsure as to the best approach.

I want to enforce conditions on the password, to ensure only strong passwords are used. I want the validation to appear on the page and also prevent the submit button from working until all the conditions are met. I've put together a quick Stackblitz example showing my code so far. What I have works, in terms of validating what the input value is, but I'm unsure of how to prevent the submit button from being pressed. I have looked into making the form dirty, but as I'm still quite new with Angular, I'm not sure how to achieve this.

I don't want to validate on clicking the submit button, I want this to be done live on the page.

I'm sure there is a better way of achieving this, but don't know how to go about it. How would I use the validation to mark the form as dirty - is this an acceptable method? Is what I've put together acceptable (I know it works, but that doesn't mean it's written correctly). Constructive criticism welcome - we all have to learn somehow!


Solution

  • What you want to use is Angular form validation: https://angular.io/guide/form-validation

    password = new FormControl('', [
      Validators.required,
      Validators.pattern(/(?=[A-Z])(?=[a-z])(?=[0-9]).{8,}/)
    ]);
    

    Your submit button already has [disabled]="registerForm.invalid". If an individual control is invalid, then the form will also be invalid.