Skip to content

Instantly share code, notes, and snippets.

@nirkaufman
Last active May 3, 2020 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nirkaufman/3a625521ec8a9d5e75b53cbbc7e32399 to your computer and use it in GitHub Desktop.
Save nirkaufman/3a625521ec8a9d5e75b53cbbc7e32399 to your computer and use it in GitHub Desktop.
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();
}
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