Last active
July 5, 2017 22:23
-
-
Save GeorgDangl/ac53a94ccd83e3b52dd0bdf8501f09ff to your computer and use it in GitHub Desktop.
Validating usernames in an Angular frontend with Asp.Net Core Identity
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
| <md-input-container> | |
| <input mdInput required di-validateUsername placeholder="Username" name="username" [(ngModel)]="registerModel.username" #username="ngModel"> | |
| <md-hint *ngIf="!username.valid && !username.pristine && username.errors && username.errors.validateUsername">Username contains illegal character: "{{username.errors.validateUsername}}"</md-hint> | |
| </md-input-container> |
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
| public class Startup | |
| { | |
| public void ConfigureServices(IServiceCollection services) | |
| { | |
| services.AddIdentity<ApplicationUser>(identityConfig => | |
| { | |
| identityConfig.User.AllowedUsernameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+ "; | |
| }); | |
| } | |
| } |
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 { Directive } from '@angular/core'; | |
| import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms'; | |
| @Directive({ | |
| selector: '[di-validateUsername]', | |
| providers: [{ provide: NG_VALIDATORS, useExisting: ValidateUsernameDirective, multi: true }] | |
| }) | |
| export class ValidateUsernameDirective implements Validator { | |
| private allowedCharacters: string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+ '; | |
| validate(control: AbstractControl): { [index: string]: any; } { | |
| if (!control.value) { | |
| return null; | |
| } | |
| if (typeof control.value !== 'string') { | |
| return { validateUsername: 'The property to validate must be of type \'string\'' }; | |
| } | |
| for (var i = 0; i < control.value.length; i++) { | |
| if (this.allowedCharacters.indexOf(control.value[i]) < 0) { | |
| return { validateUsername: control.value[i]} | |
| } | |
| } | |
| return null; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment