Last active
May 3, 2020 15:54
-
-
Save nirkaufman/3a625521ec8a9d5e75b53cbbc7e32399 to your computer and use it in GitHub Desktop.
This file contains 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 {FormControl} from "@angular/forms"; | |
@Component({ | |
selector: 'app-root', | |
template: ` | |
<h1>Angular Playground</h1> | |
<input type="password" | |
[formControl]="inputControl" | |
nkStrongPassword | |
[nkStrongPasswordOptions]="{ popup: true }" | |
> | |
<pre *ngIf="inputControl.errors"> | |
{{ inputControl.errors | json }} | |
</pre> | |
`, | |
styles:[` | |
.ng-invalid {border-color: red !important;} | |
.weak { border-color: pink !important; } | |
.strong { border-color: green !important; } | |
`] | |
}) | |
export class AppComponent { | |
inputControl = new FormControl(); | |
} | |
This file contains 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 {Directive, ElementRef, Input, Renderer2} from '@angular/core'; | |
import {AbstractControl, NG_VALIDATORS, ValidationErrors, Validator} from "@angular/forms"; | |
import estimate from 'zxcvbn'; | |
interface ValidationsErrorMessage { | |
[key: string]: { | |
message: string | |
} | |
} | |
@Directive({ | |
selector: '[nkStrongPassword]', | |
providers: [{ | |
provide: NG_VALIDATORS, | |
useExisting: StrongPasswordDirective, | |
multi: true | |
}] | |
}) | |
export class StrongPasswordDirective implements Validator { | |
@Input('nkStrongPasswordOptions') options; | |
constructor(private host: ElementRef, private renderer: Renderer2) {} | |
validate(control: AbstractControl): ValidationsErrorMessage | null { | |
if (!control.value) return null; | |
const results = estimate(control.value); | |
console.log(this.options); | |
if (results.score < 4) { | |
this.removeClass('strong'); | |
this.addClass('weak'); | |
return { | |
weakPassword: { | |
message: results.feedback | |
} | |
} | |
} else { | |
this.removeClass('weak'); | |
this.addClass('strong'); | |
return null; | |
} | |
} | |
private addClass(className: string) { | |
this.renderer.addClass(this.host.nativeElement, className); | |
} | |
private removeClass(className: string) { | |
this.renderer.removeClass(this.host.nativeElement, className); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment