Get sibling AbstractControl from Angular reactive FormArray - Custom Validation - javascript

I'm having a Contact form in Angular using a Reactive form. The form contains firstName, lastName and an Array of address. Each address formgroup contains a checkbox, if the checkbox is checked, validation of the State text box mandatory is needed, along with min and max char length.
I have written a custom validator namely "stateValidator" and I tried to get the sibling element "isMandatory" but I am not able to get the control.
I tried the following approach
control.root.get('isMandatory'); - Its returning null
control.parent.get('isMandatory'); - Its throwing exception
I found some links in stackoverflow, but there is no answer available and some answers are not giving solutions, for example the code above: control.root.get('isMandatory'); I got this from one of the video tutorials but nothing worked.
The complete working source code is available in StackBlitz: https://stackblitz.com/edit/angular-custom-validators-in-dynamic-formarray
app.component.ts
import { Component } from '#angular/core';
import { FormBuilder, FormGroup, FormArray, Validators, AbstractControl } from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
public userForm: FormGroup;
constructor(private _fb: FormBuilder) {
this.userForm = this._fb.group({
firstName: [],
lastName: [],
address: this._fb.array([this.addAddressGroup()])
});
}
private addAddressGroup(): FormGroup {
return this._fb.group({
street: [],
city: [],
state: ['', this.stateValidator],
isMandatory: [false, [Validators.required]]
});
}
get addressArray(): FormArray {
return <FormArray>this.userForm.get('address');
}
addAddress(): void {
this.addressArray.push(this.addAddressGroup());
}
removeAddress(index: number): void {
this.addressArray.removeAt(index);
}
stateValidator(control: AbstractControl): any {
if(typeof control === 'undefined' || control === null
|| typeof control.value === 'undefined' || control.value === null) {
return {
required: true
}
}
const stateName: string = control.value.trim();
const isPrimaryControl: AbstractControl = control.root.get('isMandatory');
console.log(isPrimaryControl)
if(typeof isPrimaryControl === 'undefined' || isPrimaryControl === null||
typeof isPrimaryControl.value === 'undefined' || isPrimaryControl.value === null) {
return {
invalidFlag: true
}
}
const isPrimary: boolean = isPrimaryControl.value;
if(isPrimary === true) {
if(stateName.length < 3) {
return {
minLength: true
};
} else if(stateName.length > 50) {
return {
maxLength: true
};
}
} else {
control.setValue('');
}
return null;
}
}
app.component.html
<form class="example-form" [formGroup]="userForm">
<div>
<mat-card class="example-card">
<mat-card-header>
<mat-card-title>Users Creation</mat-card-title>
</mat-card-header>
<mat-card-content>
<div class="primary-container">
<mat-form-field>
<input matInput placeholder="First Name" value="" formControlName="firstName">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Last Name" value="" formControlName="lastName">
</mat-form-field>
</div>
<div formArrayName="address">
<div class="address-container" *ngFor="let group of addressArray.controls; let i = index;"
[formGroupName]="i">
<fieldset>
<legend>
<h3>Address: {{i + 1}}</h3>
</legend>
<mat-checkbox formControlName="isMandatory">Mandatory</mat-checkbox>
<div>
<mat-form-field>
<input matInput placeholder="Street" value="" formControlName="street">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="City" value="" formControlName="city">
</mat-form-field>
<mat-form-field>
<input matInput placeholder="State" value="" formControlName="state">
</mat-form-field>
</div>
</fieldset>
</div>
</div>
<div class="form-row org-desc-parent-margin">
<button mat-raised-button (click)="addAddress()">Add more address</button>
</div>
</mat-card-content>
</mat-card>
</div>
</form>
<mat-card class="pre-code">
<mat-card-header>
<mat-card-title>Users Information</mat-card-title>
</mat-card-header>
<mat-card-content>
<pre>{{userForm.value | json}}</pre>
</mat-card-content>
</mat-card>
Kindly assist me how to get the sibling abstract control in the custom validator method.
I tried the code which was specified in the following couple of answers
isPrimaryControl = (<FormGroup>control.parent).get('isMandatory')
It's throwing an error ERROR Error: too much recursion. Kindly assist me how to fix this.

You may need to cast the parent to FormGroup, try using :
if(control.parent) {
(<FormGroup>control.parent).get('isMandatory')
}

You can get the value of isMandatory from Form control like this, i have changed your stateValidator method to basically typecast the control to concrete sub class then from the controls array you can get the formControls
stateValidator(control: AbstractControl): any {
let mandatory:boolean=false;
if(control.parent){
console.log('control',<FormGroup>control.parent.controls.isMandatory.value);
mandatory=<FormGroup>control.parent.controls.isMandatory.value;
}
if((typeof control === 'undefined' || control === null
|| typeof control.value === 'undefined' || control.value === null)&& mandatory) {
debugger;
return {
required: true
}
}
const stateName: string = control.value.trim();
let isPrimaryControl: AbstractControl=null;
if(control.parent){
isPrimaryControl=<FormGroup>control.parent.controls.isMandatory;
console.log(isPrimaryControl)
}
if(typeof isPrimaryControl === 'undefined' || isPrimaryControl === null||typeof isPrimaryControl.value === 'undefined' || isPrimaryControl.value === null) {
return {
invalidFlag: true
}
}
const isPrimary: boolean = isPrimaryControl.value;
if(isPrimary === true) {
if(stateName.length < 3) {
return {
minLength: true
};
} else if(stateName.length > 50) {
return {
maxLength: true
};
}
} else {
control.setValue('');
}
return null;
}

Related

Pass a DOM event to custom form validator in Angular

I am trying to validate a form using the reactive approach. I am using the file input to take a file from the user. I have defined a custom validator that allows the user to upload a file on certain conditions. While trying to do so, I am getting an error. The validator does not receive the event as a whole but rather only the path of the file something like C:\fakepath\abc.xlsx. I want to pass the DOM event so that I can handle all the properties of files like type, size etc.
Here's my code:
file.validator.ts
import { AbstractControl } from '#angular/forms';
export function ValidateFile(control: AbstractControl) :
{ [key: string]: boolean } | null {
const value = control.value;
if (!value) {
return null;
}
return value.length < 0 && value.files[0].type !== '.xlsx' && value.files[0].size > 5000000
? { invalidFile: true } : null;
}
sheet.component.ts
constructor(
private formBuilder: FormBuilder,
private alertService: AlertService
) {
this.sheetForm = this.formBuilder.group({
sheetType: ['Select Sheet Type', [Validators.required]],
sheetUpload: [null, [Validators.required, ValidateFile]],
sheetDescription: [
null,
[
Validators.required,
Validators.minLength(10),
Validators.maxLength(100),
],
],
});
}
sheet.component.html
<div class="input-group">
<label for="sheet-upload">Upload Sheet: </label>
<input
id="sheet-upload"
type="file"
(change)="handleFileInput($event)"
formControlName="sheetUpload"
accept=".xlsx"
/>
<small
id="custom-error-message"
*ngIf="
(sheetForm.get('sheetUpload').dirty ||
sheetForm.get('sheetUpload').touched) &&
sheetForm.get('sheetUpload').invalid
"
>
The file size exceeds 5 MB or isn't a valid excel type. Please
upload again.
</small>
</div>
Any help would be appreciated. Thanks!
Not sure if this is the best way but it works
Create a directive to attach the native element to form control
On validation get the file from the native element in the validator
And also to use formControlName you need to assign a formGroup in the parent element (ignore if included in some other parent element)
#Directive({
selector: '[formControlName]',
})
export class NativeElementInjectorDirective implements OnInit {
constructor(private el: ElementRef, private control: NgControl) {}
ngOnInit() {
(this.control.control as any).nativeElement = this.el.nativeElement;
}
}
file.validator.ts
export function ValidateFile(control: any): { [key: string]: boolean } | null {
const value = control.value;
const file = control?.nativeElement?.files[0];
if (!value) {
return null;
}
return value.length < 0 || file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.size > 5000000
? { invalidFile: true }
: null;
}
sheet.component.html
<div class="input-group" [formGroup]="sheetForm">
<label for="sheet-upload">Upload Sheet: </label>
<input
id="sheet-upload"
type="file"
formControlName="sheetUpload"
accept=".xlsx"
/>
<small
id="custom-error-message"
*ngIf="
(sheetForm.get('sheetUpload').dirty ||
sheetForm.get('sheetUpload').touched) &&
sheetForm.get('sheetUpload').invalid
"
>
The file size exceeds 5 MB or isn't a valid excel type. Please upload again.
</small>
</div>
You can get reference to input element and use it in validator.
<input #sheetUpload ...>
#ViewChild('sheetUpload') fileInput: HTMLInputElement;
private ValidateFile(): ValidatorFn {
return (control) => {
const value = control.value;
if (!value || !this.fileInput) {
return null;
}
const file = this.fileInput.files[0];
return value.length < 0 && file.type !== '.xlsx' && file.size > 5000000
? { invalidFile: file.name }
: null;
}
}

Angular forms require one of two form groups to be valid

I am trying to implement a reactive angular form where either A or B has to be entered. A is a unique id and B is a set of values which identify the id. Now I try to validate a Form that is valid if either A is entered or B is entered including all the required values. I found several solutions that implement this behavior based on FormFields but was not able to get it working with the group of values.
<form class="container" [formGroup]="myForm" (ngSubmit)="onSubmit()">
<mat-form-field class="w-1/2">
<mat-label>ID</mat-label>
<input matInput type="number" formControlName="id">
</mat-form-field>
<div class="grid grid-cols-3 gap-4" formGroupName="innerGroup">
<mat-form-field>
<mat-label>First Name</mat-label>
<input matInput type="number" formControlName="firstName">
</mat-form-field>
<mat-form-field>
<mat-label>Last Name</mat-label>
<input matInput type="number" formControlName="lastName">
</mat-form-field>
</div>
</form>
My first idea was to override the default validator for the form but I could not figure out how to do that. Not even sure if it would be possible. I was trying to adjust https://stackoverflow.com/a/48714721 to work in my scenario but I had no idea how to get it to work because of the additional complexity with the inner form group.
Using angular 14 I was able to produce a similar result to what you are describing I am not sure it will 100% solve your issue however it might help.
Basically what I did was create a validator function that is to be applied at the group level. This validator will check the valid state of any given controls be they a FormGroup or a FormControl. However, this alone will not solve the problem as if you have a form group angular will see that any underling control or group that is invalid will also invalidate the parent. So what I did was call .disable() on any control that was being checked by the validator function. This will disable the UI element and disable validation checking by angular allowing the parent to be considered valid when one of the children is valid but the other is invalid effectively creating a one and only one validator.
My specific example I was trying to get the OnlyOneValidator to work for a MatStepper.
Validator
export function onlyOneValidator(controlKeys: string[]) {
return (control: AbstractControl): ValidationErrors | null => {
let countOfValidControls = 0;
for (let key of controlKeys) {
const controlToCheck = control.get(key);
if (controlToCheck === null || controlToCheck === undefined) {
throw new Error(`Error: Invalid control key specified key was ${key}`);
}
countOfValidControls += controlToCheck?.valid ? 1 : 0;
}
if (countOfValidControls !== 1) {
// the count is not exactly one
return {
onlyOneValid: {
actualValidCount: countOfValidControls,
expectedValidCount: 1
}
};
}
return null;
};
}
Controller
#Component({
selector: "app-equipment-creation-page",
templateUrl: "./equipment-creation-page.component.html",
styleUrls: ["./equipment-creation-page.component.scss"],
})
export class EquipmentCreationPageComponent implements OnInit, OnDestroy {
public categories = [null, "Tools", "Vehicles"];
constructor(private _formBuilder: FormBuilder) {}
public categoryInformationGroup = this._formBuilder.group({
existingCategory: this._formBuilder.group({
category: new FormControl(null, [ Validators.required ])
}),
newCategory: this._formBuilder.group({
name: new FormControl("", [Validators.required]),
description: new FormControl("", [Validators.required])
})
}, {
validators: [
onlyOneValidator(["existingCategory", "newCategory"])
],
});
public ngOnDestroy(): void {
this.subscriptions.forEach(sub => {
sub.unsubscribe();
});
}
private subscriptions: Subscription[] = [];
public ngOnInit(): void {
this.subscriptions.push(this.categoryInformationGroup.controls.existingCategory.statusChanges.pipe(
tap((status: string) => {
if (status === "VALID") {
this.categoryInformationGroup.controls.newCategory.disable();
} else {
this.categoryInformationGroup.controls.newCategory.enable();
}
})
).subscribe());
this.subscriptions.push(this.categoryInformationGroup.controls.newCategory.statusChanges.pipe(
tap((status: string) => {
if (status === "VALID") {
this.categoryInformationGroup.controls.existingCategory.disable();
} else {
this.categoryInformationGroup.controls.existingCategory.enable();
}
})
).subscribe());
}
}
Template
<form [formGroup]="categoryInformationGroup.controls.existingCategory">
<mat-form-field>
<mat-label>Apply to existing category?</mat-label>
<mat-select formControlName="category">
<mat-option *ngFor="let category of categories" [value]="category">
{{ category ?? "None" }}
</mat-option>
</mat-select>
</mat-form-field>
</form>
OR
<form [formGroup]="categoryInformationGroup.controls.newCategory">
<mat-form-field>
<mat-label>Create New Category</mat-label>
<input matInput formControlName="name" placeholder="Name">
<mat-error *ngIf="categoryInformationGroup.controls.newCategory.controls.name.hasError('required')">This field
is required
</mat-error>
</mat-form-field>
<mat-form-field>
<mat-label>Create New Category</mat-label>
<input matInput formControlName="description" placeholder="Description">
<mat-error *ngIf="categoryInformationGroup.controls.newCategory.controls.description.hasError('required')">
This field is required
</mat-error>
</mat-form-field>
</form>
Hopefully this helps or at least gives you some ideas about how to approach this. If anyone else has any thoughts on this please let me know I would love to find a better way to do this.

Mat-Error Required validation error message shows when form is first open

I have a custom control component that is used to show a required validation error for mat-chip-lists. On the form that I'm using this component, when I first open this form the required validation message shows. I only want it to show when the field is not populated with any data. Can someone please provide a reason why and a solution to what I need to do to get the validation to work properly.
I could be overcomplicating this and it's much simpler than I thought.
html where mat-error element for required show:
<mat-form-field [floatLabel]="floatLabel">
<mat-label>{{ label }}</mat-label>
<mat-chip-list #optionList aria-label="label" required>
<mat-chip *ngFor="let item of selectedOptions" (removed)="removed(item)"
[removable]="!item.disabled" [disabled]="item.disabled">
{{ item.text }}
<mat-icon *ngIf="!item.disabled" matChipRemove>cancel</mat-icon>
</mat-chip>
<input
#optionInput
type="text"
[placeholder]="placeholder"
[formControl]="formControl"
[matAutocomplete]="optionAutoComplete"
[matChipInputFor]="optionList"
[required]="required"
/>
</mat-chip-list>
<mat-autocomplete #optionAutoComplete="matAutocomplete"
(optionSelected)="selected($event.option.value)">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{ option.text }}
</mat-option>
</mat-autocomplete>
<mat-hint *ngIf="hint">{{ hint }}</mat-hint>
</mat-form-field>
<mat-error *ngIf="required === true && hasValue === false &&
isInitialized === true"> {{ label }} is
<strong>required</strong> </mat-error>
Typescript for the custom control
The removed function fires when you remove selected items from the list. It turns the check back on and sends the update to the parent component.
Component({
selector: 'app-chips',
templateUrl: './chips.component.html',
})
export class ChipsComponent implements OnInit, DoCheck {
#Input() label = '';
#Input() placeholder = '';
#Input() options: Options[] = [];
#Input() selectedOptions: Options[] = [];
#Input() floatLabel: FloatLabelType = 'auto';
#Input() hint!: string | undefined;
#Input() required = true;
hasValue: boolean = this.selectedOptions.length > 0;
isInitialized: boolean | undefined;
#ViewChild('optionInput') optionInput: ElementRef | undefined;
#Output() onRemoved = new EventEmitter<Options>();
#Output() selectedOptionsChanged = new EventEmitter<Options[]>();
formControl = new FormControl('');
filteredOptions: Observable<Options[]> | undefined;
iterableDiffer: IterableDiffer<Options>;
constructor(private readonly iterableDiffers: IterableDiffers) {
this.iterableDiffer = this.iterableDiffers.find([]).create();
}
ngDoCheck(): void {
const optionChanges = this.iterableDiffer.diff(this.options);
if (optionChanges) {
this.filteredOptions = of(this.options);
}
if (this.required === undefined) {
this.required = false;
}
}
ngOnInit(): void {
this.subscribeFilterOptions();
this.isInitialized = true;
}
ngAfterViewInit(): void {
this.isInitialized = true;
}
selected(value: Options): void {
if (this.optionInput) {
this.optionInput.nativeElement.value = '';
}
if (!this.selectedOptions.find((x) => x.text === value.text)) {
this.selectedOptions.push(value);
this.selectedOptionsChanged.emit(this.selectedOptions);
}
this.hasValue = this.selectedOptions.length > 0;
}
private subscribeFilterOptions() {
this.filteredOptions = this.formControl.valueChanges.pipe(
startWith(''),
map((value: string | Options) =>
value && typeof value === 'string' ? this.options.filter((o) =>
o.text.toLowerCase().includes(value.toLowerCase())) :
this.options.slice()
)
);
}
removed(value: Options): void {
this.onRemoved.emit(value);
this.hasValue = this.selectedOptions.length > 0;
}
}
Mat-chip-list component on the form
<div class="col-md-12">
<app-linq-chips
label="Entities"
placeholder="Add Entity..."
[options]="entityOptions"
[selectedOptions]="selectedEntities"
[hint]="
entityListHasDisabledOptions === true
? 'Please remove this contact from any roles for an entity prior to removing their
association to that entity.'
: undefined
"
(onRemoved)="removeEntity($event)"
>
</app-linq-chips>
</div>
Your variable hasValue is only set when a chip is selected or removed. When the component is initialized it's value is false as the number of selected options is zero.
hasValue: boolean = this.selectedOptions.length > 0;
The required variable is initialized to true, so the mat error condition below:
<mat-error *ngIf="required === true && hasValue === false"> {{ label }} is
<strong>required</strong> </mat-error>
will be true, so the error will show initially.
To fix this issue, add an extra boolean variable, isInitialized (or whatever you want to name it), set it to false in the ngOnInit(), then set it to true in the ngAfterViewinit().
Update your mat-error condition like follows:
<mat-error *ngIf="required === true && hasValue === false && isInitialized === true"> {{ label }} is
<strong>required</strong> </mat-error>
Try the above and it should only error check after the component selections are made.

Angular 5 - Uncheck all checkboxes function is not affecting view

I'm trying to include a reset button on a Reactive form in Angular 5. For all form fields, the reset is working perfectly except for the multiple checkboxes, which are dynamically created.
Actually the reset apparently happens for the checkboxes as well, but the result is not reflected in the view.
service.component.html
<form [formGroup]="f" (ngSubmit)="submit()">
<input type="hidden" id="$key" formControlName="$key">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" formControlName="name">
</div>
<br/>
<p>Professionals</p>
<div formArrayName="prof">
<div *ngFor="let p of professionals | async; let i = index">
<label class="form-check-label">
<input class="form-check-input" type="checkbox (change)="onChange({name: p.name, id: p.$key}, $event.target.checked)" [checked]="f.controls.prof.value.indexOf(p.name) > -1"/>{{ p.name }}</label>
</div>
<pre>{{ f.value | json }}</pre>
</div>
<br/>
<button class="btn btn-success" type="submit" [disabled]="f?.invalid">Save</button>
<button class="btn btn-secondary" type="button" (click)="resetForm($event.target.checked)">Reset</button>
</form>
service.component.ts
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormControl, FormGroup, Validators, FormArray } from '#angular/forms'
import { AngularFireAuth } from 'angularfire2/auth';
import { Router, ActivatedRoute } from '#angular/router';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable} from 'angularfire2/database';
import { Service } from './service';
export class ServiceComponent implements OnInit {
f: FormGroup;
userId: string;
$key: string;
value: any;
services: FirebaseListObservable<Service[]>;
service: FirebaseObjectObservable<Service>;
professionals: FirebaseListObservable<Service[]>;
profs: FirebaseListObservable<Service[]>;
constructor(private db: AngularFireDatabase,
private afAuth: AngularFireAuth,
private route: ActivatedRoute,
private router: Router,
private fb: FormBuilder) {
this.afAuth.authState.subscribe(user => {
if(user) this.userId = user.uid
this.services = db.list(`services/${this.userId}`);
})
this.afAuth.authState.subscribe(user => {
if(user) this.userId = user.uid
this.professionals = this.db.list(`professionals/${this.userId}`);
})
}
ngOnInit() {
// build the form
this.f = this.fb.group({
$key: new FormControl(null),
name: this.fb.control('', Validators.required),
prof: this.fb.array([], Validators.required)
})
}
onChange(name:string, isChecked: boolean) {
const profArr = <FormArray>this.f.controls.prof;
if(isChecked) {
profArr.push(new FormControl(name));
console.log(profArr.value);
} else {
let index = profArr.controls.findIndex(x => x.value == name)
profArr.removeAt(index);
console.log(profArr.value);
}
}
resetForm(){
let profArr = <FormArray>this.f.controls.prof;
this.f.controls.name.setValue('');
profArr.controls.map(x => x.patchValue(false));
this.f.controls.$key.setValue(null);
}
}
service.ts
export class Service {
$key: string;
name: string;
professionals: string[];
}
The result of the code above, displayed by line <pre> {{f.value | json}} </ pre> is:
When I fill out the form:
{
"$key": null,
"name": "Test service",
"prof": [
{
"name": "Ana Marques",
"id": "-LEZwqy3cI3ZoYykonWX"
},
{
"name": "Pedro Campos",
"id": "-LEZz8ksgp_kItb1u7RE"
}
]
}
When I click on Reset button:
{
"$key": null,
"name": "",
"prof": [
false,
false
]
}
But checkboxes are still selected:
What is missing?
I would stop using FormControls to handle what is basically state.
You have some code which loads the professionals property of the component. Just add to that data a checked property and change the type of professionals to Service[]:
this.db.list(`professionals/${this.userId}`)
.subscribe(professionals => {
professionals.forEach(p => p.checked = false);
this.professionals = professional;
});
Btw, you don't have a checked property on your Service type, so either you extend it or transform professionals in something else (i.e. a CheckableService).
The template becomes:
<div *ngFor="let p of professionals; let i = index">
<label class="form-check-label">
<input class="form-check-input" type="checkbox (change)="onChange(p, $event.target.checked)" [checked]="p.checked"/>{{ p.name }}</label>
</div>
And the onChange method becomes:
onChange(professional: Service, isChecked: boolean) {
professional.checked = isChecked;
this.profArr = this.professionals.filter(p => p.checked);
}
It seems a lot cleaner to me (you will need to adjust for the checked parameter not being in the Service type, but the code is simply adaptable). No messing with controls, only data cleanly flowing through your component.
You are not referencing your checkboxes. Give them a name using the index.
<div formArrayName="prof">
<div *ngFor="let p of professionals | async; let i = index">
<label class="form-check-label">
<input [formControlName]="i" class="form-check-input" type="checkbox (change)="onChange({name: p.name, id: p.$key}, $event.target.checked)" [checked]="f.controls.prof.value.indexOf(p.name) > -1"/>{{ p.name }}</label>
</div>
<pre>{{ f.value | json }}</pre>
</div>
This is my checkall checkbox
<input type="checkbox" value="a" (click)="checkAll" [checked]="checkAll">
This i a regular checkbox, i used this whithin an ngfor
<input type="checkbox" value="a" (click)="check(object)" name="checkbox" [checked]="true">
And the checkall checkboxes function
let elements = document.getElementsByTagName('input');
if (this.checkAll) {
this.checkAll = false;
for (let i = 0; i < elements.length; i++) {
if (elements[i].type == 'checkbox') {
elements[i].checked = false;
}
}
}
else....the other way

Custom Validator on reactive form for password and confirm password matching getting undefined parameters into Angular 4

I'm trying to implement a custom validator to check if the password and password confirm are equal. The problem is that the validator is getting undefined password and confirmedPassword parameters. How do I make this work. The function works cause if I change the condition to === instead of !== it throws the error correctly when the fields are the same. Does anyone know which is the error here?
signup.component.html
<div class="col-md-7 col-md-offset-1 col-sm-7">
<div class="block">
<div class="well">
<form (onSubmit)="onSubmit()" [formGroup]="signUpForm">
<div class="form-group">
<label for="username" class="control-label">Nombre de usuario:</label>
<input type="text" class="form-control" formControlName="username" title="Please enter your username" placeholder="username">
<p class="help-block" *ngIf="signUpForm.get('username').hasError('required') && signUpForm.get('username').touched">El nombre de usuario es obligatorio</p>
<p class="help-block" *ngIf="signUpForm.get('username').hasError('minlength') && signUpForm.get('username').touched">El nombre de usuario debe tener al menos 6 caracteres</p>
<p class="help-block" *ngIf="signUpForm.get('username').hasError('maxlength') && signUpForm.get('username').touched">El nombre de usuario debe tener menos de 15 caracteres</p>
</div>
<div class="form-group">
<label for="email" class="control-label">E-mail:</label>
<input class="form-control" formControlName="email" title="Please enter your email" placeholder="example#gmail.com">
<p class="help-block" *ngIf="signUpForm.get('email').hasError('required') && signUpForm.get('email').touched">La dirección de email es obligatoria</p>
<p class="help-block" *ngIf="signUpForm.get('email').hasError('email') && signUpForm.get('email').touched">Debe ingresar una dirección de correo válida</p>
</div>
<div class="form-group">
<label for="password" class="control-label">Contraseña:</label>
<input type="password" class="form-control" formControlName="password" title="Please enter your password" [(ngModel)]="password">
<p class="help-block" *ngIf="signUpForm.get('password').hasError('required') && signUpForm.get('password').touched">Debe ingresar una contraseña</p>
</div>
<div class="form-group">
<label for="confirmedPassword" class="control-label">Confirmar Contraseña:</label>
<input type="password" class="form-control" formControlName="confirmedPassword" title="Please re-enter your password" [(ngModel)]="confirmedPassword">
<p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('required') && signUpForm.get('confirmedPassword').touched">La confirmación de contraseña no puede estar vacía</p>
<p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('passwordMismatch') && signUpForm.get('confirmedPassword').touched">Las contraseñas no coinciden</p>
</div>
<button type="submit" class="btn btn-success" [disabled]="!signUpForm.valid">Registrarse</button>
<a routerLink="/signin" class="btn btn-default" style="">Ya tenes usuario? Logueate</a> {{ creationMessage }}
</form>
</div>
</div>
</div>
signup.component.ts
import { Component, OnInit, ViewChild, Input } from '#angular/core';
import { FormControl, FormGroup, Validators } from '#angular/forms';
import { CustomValidators } from '../../shared/custom-validators';
import { Observable } from 'rxjs/Observable';
#Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.sass']
})
export class SignupComponent implements OnInit {
signUpForm: FormGroup;
user = {
username: '',
email: '',
password: ''
};
submitted = false;
#Input() password='';
#Input() confirmedPassword='';
constructor() { }
ngOnInit() {
this.signUpForm = new FormGroup({
'username': new FormControl(null, [Validators.required, Validators.minLength(6), Validators.maxLength(15)]),
'email': new FormControl(null, [Validators.required, Validators.email, Validators.minLength(5)]),
'password': new FormControl(null, [Validators.required]),
'confirmedPassword': new FormControl(null, [Validators.required, CustomValidators.passwordsMatch(this.password,this.confirmedPassword).bind(this)])
});
}
onSubmit() {
if (this.signUpForm.valid) {
console.log(this.signUpForm.value);
}
}
}
custom-validators.ts
import { FormControl } from '#angular/forms';
export class CustomValidators{
public static passwordsMatch(password: string, confirmedPassword: string) {
return (control: FormControl) : { [s: string]: boolean } =>{
//getting undefined values for both variables
console.log(password,confirmedPassword);
//if I change this condition to === it throws the error if the
// two fields are the same, so this part works
if (password !== confirmedPassword) {
return { 'passwordMismatch': true }
} else {
//it always gets here no matter what
return null;
}
}
}
}
import {AbstractControl, FormBuilder, FormGroup, Validators} from
set your password input into the group and no need to use "ngModel".
<div class="form-group row" formGroupName="passwords">
<div class="form-group">
<label for="password" class="control-label">Contraseña:</label>
<input type="password" class="form-control" formControlName="password" title="Please enter your password">
<p class="help-block" *ngIf="signUpForm.get('password').hasError('required') && signUpForm.get('password').touched">Debe ingresar una contraseña</p>
</div>
<div class="form-group">
<label for="confirmedPassword" class="control-label">Confirmar Contraseña:</label>
<input type="password" class="form-control" formControlName="confirmedPassword" title="Please re-enter your password">
<p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('required') && signUpForm.get('confirmedPassword').touched">Password must be required</p>
<p class="help-block" *ngIf="signUpForm.get('confirmedPassword').hasError('passwordMismatch') && signUpForm.get('confirmedPassword').touched">password does not match</p>
</div>
buildForm(): void {
this.userForm = this.formBuilder.group({
passwords: this.formBuilder.group({
password: ['', [Validators.required]],
confirm_password: ['', [Validators.required]],
}, {validator: this.passwordConfirming}),
});
}
add this custom function for validate password and confirm password
passwordConfirming(c: AbstractControl): { invalid: boolean } {
if (c.get('password').value !== c.get('confirm_password').value) {
return {invalid: true};
}
}
Display error when password does not match
<div style='color:#ff7355' *ngIf="userForm.get(['passwords','password']).value != userForm.get(['passwords','confirm_password']).value && userForm.get(['passwords','confirm_password']).value != null">
Password does not match</div>
The issue is that you are mixing the reactive forms module with the input approach. This is causing you to get undefined when passing the values to the validator.
You don't need to bind to the ng-model when using the reactive forms. Instead, you should access the value of the fields from the Instance of FormGroup.
I do something like this in an app to validate the passwords match.
public Credentials: FormGroup;
ngOnInit() {
this.Credentials = new FormGroup({});
this.Credentials.addControl('Password', new FormControl('', [Validators.required]));
this.Credentials.addControl('Confirmation', new FormControl(
'', [Validators.compose(
[Validators.required, this.validateAreEqual.bind(this)]
)]
));
}
private validateAreEqual(fieldControl: FormControl) {
return fieldControl.value === this.Credentials.get("Password").value ? null : {
NotEqual: true
};
}
Note that the validator expects a FormControl field as a parameter and it compares the value of the field to that of the value of the Password field of the Credentials FormGroup.
In the HTML make sure to remove the ng-model.
<input type="password" class="form-control" formControlName="confirmedPassword" title="Please re-enter your password" >
<!-- AND -->
<input type="password" class="form-control" formControlName="password" title="Please enter your password">
Hope this helps!
There are two types of validators: FormGroup validator and FormControl validator. To verify two passwords match, you have to add a FormGroup validator. Below is my example:
Note: this.fb is the injected FormBuilder
this.newAccountForm = this.fb.group(
{
newPassword: ['', [Validators.required, Validators.minLength(6)]],
repeatNewPassword: ['', [Validators.required, Validators.minLength(6)]],
},
{validator: this.passwordMatchValidator}
);
passwordMatchValidator(frm: FormGroup) {
return frm.controls['newPassword'].value === frm.controls['repeatNewPassword'].value ? null : {'mismatch': true};
}
and in the templeate:
<div class="invalid-feedback" *ngIf="newAccountForm.errors?.mismatch && (newAccountForm.controls['repeatNewPassword'].dirty || newAccountForm.controls['repeatNewPassword'].touched)">
Passwords don't match.
</div>
The key point here is to add the FormGroup validator as the second parameter to the group method.
Please update FormGroup code like below in Angular5
this.signUpForm = new FormGroup({
'username': new FormControl(null, [Validators.required, Validators.minLength(6), Validators.maxLength(15)]),
'email': new FormControl(null, [Validators.required, Validators.email, Validators.minLength(5)]),
'password': new FormControl(null, [Validators.required]),
'confirmedPassword': new FormControl(null, [Validators.required])
}, this.pwdMatchValidator);
Add pwdMatchValidator function in your component
pwdMatchValidator(frm: FormGroup) {
return frm.get('password').value === frm.get('confirmedPassword').value
? null : {'mismatch': true};
}
Add validation message in your template
<span *ngIf="confirmedPassword.errors || signUpForm .errors?.mismatch">
Password doesn't match
</span>
Please find the below angular material working component.
Component Templete Code password.component.html
<form class="cahnge-pwd-form" (ngSubmit)="onSubmit()" name="passwordForm" [formGroup]="passwordForm" #formDir="ngForm">
<div fxLayout='column'>
<mat-form-field>
<input matInput name="password" placeholder="Password" [type]="hide ? 'text' : 'password'" formControlName="password" required>
<mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility_off' : 'visibility'}}</mat-icon>
<mat-error *ngIf="password.invalid && (password.dirty || password.touched || isSubmit)">
<span *ngIf="password.errors.required">
Please enter a Password.
</span>
<span *ngIf="password.errors.maxlength">
Please enter a Email no more than 16 characters.
</span>
<span *ngIf="password.errors.minlength">
Please enter a password at least 6 characters.
</span>
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput name="password" placeholder="Confirm Password" [type]="confirm_hide ? 'text' : 'password'" formControlName="confirm_password"
required>
<mat-icon matSuffix (click)="confirm_hide = !confirm_hide">{{confirm_hide ? 'visibility_off' : 'visibility'}}</mat-icon>
<mat-error *ngIf="(confirm_password.invalid && (confirm_password.dirty || confirm_password.touched || isSubmit) || passwordForm.errors?.mismatch)">
<span *ngIf="confirm_password.errors || passwordForm.errors?.mismatch">
Password doesn't match
</span>
</mat-error>
</mat-form-field>
<div fxLayout='row' fxLayoutGap="10px">
<button type="submit" mat-raised-button color="primary">Submit</button>
<button type="button" (click)="formDir.resetForm(passwordForm)" mat-raised-button color="warn">Cancel</button>
</div>
</div>
</form>
Component Code : password.component.ts
import { Component, OnInit, AfterViewInit } from '#angular/core';
import { FormControl, FormGroup, Validators, FormBuilder } from '#angular/forms';
import { ToastrService } from 'ngx-toastr';
import { Router, ActivatedRoute, ParamMap } from '#angular/router';
import { PasswordService } from './password.service';
import { PasswordValidation } from './confirm';
#Component({
selector: 'app-password',
templateUrl: './password.component.html',
styleUrls: ['./password.component.css']
})
export class PasswordComponent implements OnInit {
passwordForm: FormGroup;
isSubmit: boolean;
constructor(private router: Router, private passwordService: PasswordService, private toastrService: ToastrService, private route: ActivatedRoute) { }
ngOnInit() {
this.passwordForm = new FormGroup({
'password': new FormControl('', [
Validators.required,
Validators.minLength(6),
Validators.maxLength(16),
]),
'confirm_password': new FormControl('', [
Validators.required,
Validators.minLength(6),
Validators.maxLength(16),
]),
}, this.pwdMatchValidator);
}
pwdMatchValidator(frm: FormGroup) {
return frm.get('password').value === frm.get('confirm_password').value
? null : {'mismatch': true};
}
get password() { return this.passwordForm.get('password'); }
get confirm_password() { return this.passwordForm.get('confirm_password'); }
onSubmit(formvalue):boolean {
this.isSubmit = true;
if (this.passwordForm.invalid) {
return false;
} else {
this.passwordService.updatePassword(this.passwordForm.value)
.subscribe((res) => {
if (res.status == 'success') {
this.toastrService.success(res.msg);
this.router.navigate(['/change-password']);
}
})
return true;
}
}
}
I would do the same as Shailesh Ladumor but adding the following line before returning in the validation function:
c.get('confirm_password').setErrors({'noMatch': true});
So that the validation function looks like this:
passwordConfirming(c: AbstractControl): { invalid: boolean } {
if (c.get('password').value !== c.get('confirm_password').value) {
c.get('confirm_password').setErrors({'noMatch': true});
return {invalid: true};
}
}
This will not only set the hole userForm as an invalid form group, but it will also set confirm_password as an invalid form control.
With this you can later call the following function in your template:
public getPasswordConfirmationErrorMessage() {
if (this.userForm.get('confirm_password').hasError('required')) {
return 'You must retype your password';
} else if (this.userForm.get('confirm_password').hasError('noMatch')) {
return 'Passwords do not match';
} else {
return '';
}
}
When you need to validate on more than one field, and you wish to declare validator at form creation time, FormGroup validator must be used. The main issue with form validator is that it attaches error to form and not to validating control, which leeds to some inconsistents in template. Here is reusable form validator wich attaches error to both form and control
// in validators.ts file
export function controlsEqual(
controlName: string,
equalToName: string,
errorKey: string = controlName // here you can customize validation error key
) {
return (form: FormGroup) => {
const control = form.get(controlName);
if (control.value !== form.get(equalToName).value) {
control.setErrors({ [errorKey]: true });
return {
[errorKey]: true
}
} else {
control.setErrors(null);
return null
}
}
}
// then you can use it like
ngOnInit() {
this.vmForm = this.fb.group({
username: ['', [Validators.required, Validators.email]],
password: ['', [
Validators.required,
Validators.pattern('[\\w\\d]+'),
Validators.minLength(8)]],
confirm: [''], // no need for any validators here
}, {
// here we attach our form validator
validators: controlsEqual('confirm', 'password')
});
}
this.myForm = this.fb.group({
userEmail: [null, [Validators.required, Validators.email]],
pwd: [null, [Validators.required, Validators.minLength(8)]],
pwdConfirm: [null, [Validators.required]],
}, {validator: this.pwdConfirming('pwd', 'pwdConfirm')});
pwdConfirming(key: string, confirmationKey: string) {
return (group: FormGroup) => {
const input = group.controls[key];
const confirmationInput = group.controls[confirmationKey];
return confirmationInput.setErrors(
input.value !== confirmationInput.value ? {notEquivalent: true} : null
);
};
}
Just want to add. I use Reactive form, so it is easy to use subscription for valueChanges on the form for custom validation
this.registrationForm.valueChanges.subscribe(frm => {
const password = frm.password;
const confirm = frm.confirmPassword;
if (password !== confirm) {
this.registrationForm.get('confirmPassword').setErrors({ notMatched: true });
}
else {
this.registrationForm.get('confirmPassword').setErrors(null);
}
});
}
When you're creating the validator, you're passing in the values of password and confirmedPassword, but changes in those values will not be reflected in the validator.
The two options I see are:
define your validator on the FormGroup, and look up the values from the two controls you want to compare; or
since you're binding to this already, use this.password and this.confirmedPassword in your validator.
Just for the variety, I'm adding one more way to do this. Basically, I created a simple custom validator that takes the original control (first entered field) and checks it's value with the re-entry control (second control).
import { AbstractControl, ValidatorFn } from "#angular/forms";
export abstract class ReEnterValidation {
static reEnterValidation(originalControl: AbstractControl): ValidatorFn {
return (control: AbstractControl): { [s: string]: boolean } => {
if (control.value != originalControl.value) {
return { 'reentry': true };
}
};
}
}
You can either set this validator initially when creating a new form control:
control1 = new FormControl('', ReEnterValidation.reEnterValidation(control2));
Or, you can set it afterwards:
control.setValidators(ReEnterValidation.reEnterValidation(this._newPinControl));
control.updateValueAndValidity();
In the view, you can show the errors as following:
<!-- Confirm pin validation -->
<div *ngIf="control2.invalid && (control2.dirty || control2.touched)">
<div *ngIf="control2.errors.reentry">
The re-entered password doesn't match. Please try again.
</div>
</div>
import { AbstractControl, FormControl, FormGroup, Validators } from '#angular/forms';
public newForm: FormGroup | any;
ngOnInit(): void {
this.newForm = new FormGroup({
password: new FormControl(null, [Validators.required]),
confirm: new FormControl(null, [Validators.required])
}, {validators: this.validateAreEqual})
}
public validateAreEqual(c: AbstractControl): {notSame: boolean} {
return c.value.password === c.value.confirm ? {notSame: false} : {notSame: true};
}
<span class="error-text" *ngIf="newForm.get('confirm').touched && newForm.errors['notSame']">Password mismatch </span>

Categories

Resources