Last active
June 24, 2025 08:46
-
-
Save guillefd/3ee6c6899d21661f218c3c7ed9586e68 to your computer and use it in GitHub Desktop.
Angular Form Validator: Password Strength with upper, lower and number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <form [formGroup]="form"> | |
| <input type="password" | |
| formControlName="password"> | |
| <p class="help is-danger" | |
| *ngIf="form.get('password').hasError('strong')"> | |
| Must have at least one number, one lowercase and one uppercase letter.</p> | |
| </form> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Component } from '@angular/core'; | |
| import { FormBuilder, FormGroup, Validators } from '@angular/forms'; | |
| import { PasswordValidator } from 'password.validator'; | |
| @Component({ | |
| selector: 'form', | |
| templateUrl: './form.component.html', | |
| styleUrls: ['./form.component.scss'] | |
| }) | |
| export class Form { | |
| form: FormGroup; | |
| constructor(private fb: FormBuilder) { | |
| this.form = this.fb.group({ | |
| password: ['', [PasswordValidator.strong] | |
| ], | |
| }); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { FormControl } from '@angular/forms'; | |
| export interface ValidationResult { | |
| [key: string]: boolean; | |
| } | |
| export class PasswordValidator { | |
| public static strong(control: FormControl): ValidationResult { | |
| let hasNumber = /\d/.test(control.value); | |
| let hasUpper = /[A-Z]/.test(control.value); | |
| let hasLower = /[a-z]/.test(control.value); | |
| // console.log('Num, Upp, Low', hasNumber, hasUpper, hasLower); | |
| const valid = hasNumber && hasUpper && hasLower; | |
| if (!valid) { | |
| // return what´s not valid | |
| return { strong: true }; | |
| } | |
| return null; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment