Skip to content

Commit 1a3a0f2

Browse files
committed
Custom validator with parameter
1 parent cc6cf5e commit 1a3a0f2

File tree

3 files changed

+7
-5
lines changed

3 files changed

+7
-5
lines changed

reactive-forms/src/app/app.component.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ <h2>Registration Form</h2>
99
<div *ngIf="userName.invalid && userName.touched">
1010
<small class="text-danger" *ngIf="userName.errors?.required">Username is required</small>
1111
<small class="text-danger" *ngIf="userName.errors?.minlength">Username must be at least 3 characters</small>
12-
<small class="text-danger" *ngIf="userName.errors?.forbiddenName">{{userName.errors?.forbiddenName.value}} username not allowed</small>
12+
<small class="text-danger" *ngIf="userName.errors?.forbiddenName">'{{userName.errors?.forbiddenName.value}}' username not allowed</small>
1313
</div>
1414
</div>
1515

reactive-forms/src/app/app.component.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ export class AppComponent {
2323
// });
2424

2525
registrationForm = this.fb.group({
26-
userName: ['', [Validators.required, Validators.minLength(3), forbiddenNameValidator]],
26+
userName: ['', [Validators.required, Validators.minLength(3), forbiddenNameValidator(/password/)]],
2727
password: [''],
2828
confirmPassword: [''],
2929
address: this.fb.group({
Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { ValidatorFn, AbstractControl } from '@angular/forms';
22

3-
export function forbiddenNameValidator(control: AbstractControl): {[key: string]: any} | null {
4-
const forbidden = /admin/.test(control.value);
5-
return forbidden ? { 'forbiddenName': { value: control.value } } : null;
3+
export function forbiddenNameValidator(forbiddenName: RegExp): ValidatorFn {
4+
return (control: AbstractControl): { [key: string]: any } | null => {
5+
const forbidden = forbiddenName.test(control.value);
6+
return forbidden ? { 'forbiddenName': { value: control.value } } : null;
7+
};
68
}

0 commit comments

Comments
 (0)