RSS

Custom Group Validation in Angular 2

28 אוג

 

Angular 2 has improved the way we write custom validation. There are a lot of articles of how to do it. In this post I want to focus on how to build custom group validation in model driven development. I will build a custom group validation (CGV) that checks each item in the formArray that has a unique value.

The code for the model:

namesArray = new FormArray([], this.customGroupValidation );
myForm =
new
FormGroup({
    inputName:
new FormControl("
),
    names    :
this
.namesArray
});

 

I use the FormArray class instead of FormGroup in the names field because the number of names is unknown; it is dynamic. The user can add multiple names.

 

The template code:

 

<form [formGroup]="myForm">
    name : <
input type="text" formControlName="inputName"
>
    <
button (click)="add()">Add</button><br
>
    <
hr
>
    <
div class="left"
>
        names: <
br
>
        <
ul formArrayName="names"
>
            <
li *ngFor="let item of namesArray.controls; let i = index"
>
                <
input type="text" [formControlName]="i"
>
                <
button (click)="removeAt(i)">X</button><br
>
            </
li
>
        </
ul
>
        <
div *ngIf="namesArray.hasError('duplicate')"
>
            duplicate entries
        </
div
>
    </
div
>
</
form
>

 

clip_image002

The code for add and remove names:

add(){
   
this
.namesArray.push(
       
new FormControl(this.myForm.get('inputName'
).value)
    );
}
removeAt(i:
number
){
   
this
.namesArray.removeAt(i);
}

 

Now let’s see the custom group validation method. I used groupBy method of lodash library to detect if there are any groups of more than one item, which means that we have duplicate names.

customGroupValidation (formArray) {
   
let isError = false
;
   
var
result = _.groupBy( formArray.controls , c => c.value );
   
for (let prop in
result) {
       
if (result[prop].length > 1
) {

            isError = true;
            _.forEach(result[prop],
function
(item:FormControl) {
                item._status =
"INVALID";

           
});
        }
else
{
            result[prop][
0]._status = 'VALID';           

       
}
    }
   
if(isError){ return {'duplicate':'duplicate entries'
}}
}

 

The result of the custom group validation is that every time we add or change name to a value that already exists in the formArray, the two formControl with the same value will be invalid. In addition the parent formArray will also be invalid.

clip_image004

If I delete or change one of the duplicates names, the form will go back to be valid (in this case ‘Eyal’ name).

I hope this information was helpful for you. Try the live example.

This is one of many examples that I show in my AngularJS 2 course (.html"ng-course).

The next course opens on 18 September. For more information click .html"heHYPERLINK "http://ng-course.org/ng-course/courses/angular2.html"rHYPERLINK "http://ng-course.org/ng-course/courses/angular2.html"e.

מודעות פרסומת
 
השארת תגובה

פורסם ע"י ב- אוגוסט 28, 2016 ב- Angular 2.0, AngularJS Tips

 

להשאיר תגובה

הזינו את פרטיכם בטופס, או לחצו על אחד מהאייקונים כדי להשתמש בחשבון קיים:

הלוגו של WordPress.com

אתה מגיב באמצעות חשבון WordPress.com שלך. לצאת מהמערכת / לשנות )

תמונת Twitter

אתה מגיב באמצעות חשבון Twitter שלך. לצאת מהמערכת / לשנות )

תמונת Facebook

אתה מגיב באמצעות חשבון Facebook שלך. לצאת מהמערכת / לשנות )

תמונת גוגל פלוס

אתה מגיב באמצעות חשבון Google+ שלך. לצאת מהמערכת / לשנות )

מתחבר ל-%s

 
%d בלוגרים אהבו את זה: