Skip to content

Instantly share code, notes, and snippets.

@GeorgDangl
Last active July 5, 2017 22:23
Show Gist options
  • Select an option

  • Save GeorgDangl/ac53a94ccd83e3b52dd0bdf8501f09ff to your computer and use it in GitHub Desktop.

Select an option

Save GeorgDangl/ac53a94ccd83e3b52dd0bdf8501f09ff to your computer and use it in GitHub Desktop.
Validating usernames in an Angular frontend with Asp.Net Core Identity
<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>
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<ApplicationUser>(identityConfig =>
{
identityConfig.User.AllowedUsernameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+ ";
});
}
}
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