Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply form validation without <form> tag in Angular2

Tags:

angular

I was wondering if there is a way to validate a form in Angular 2 without using the form tag? For example below I want to make it a required field

<div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name">
</div>
<button type="button" class="btn btn-default" (click)="save()">Save</button>
like image 721
user3797088 Avatar asked Sep 13 '16 05:09

user3797088


People also ask

Can we use FormControl without form?

Yes, you can use FormControlDirective without FormGroup.

How do I add validation in template-driven form?

To add validation to a template-driven form, you add the same validation attributes as you would with native HTML form validation. Angular uses directives to match these attributes with validator functions in the framework.

Which form needs custom validator directive that wrap validation function for form validation?

Reactive forms define custom validators as functions that receive a control to validate. Template-driven forms are tied to template directives, and must provide custom validator directives that wrap validation functions.


2 Answers

Form controls can be standalone (without a parent form), whether using declarative form controls or reactive form controls.

For declarative (using ngModel) you can just do something like

<input #model="ngModel" [(ngModel)]="value" type="text" required/> <div *ngIf="model.invalid" style="color: red">Required</div> 

For reactive forms you can do something like

<input [formControl]="control" [(ngModel)]="value" type="text"/> <div *ngIf="control.invalid" style="color: red">Required</div>  // in component this.control = new FormControl('', [Validators.required]); 

See Plunker

For more information on using Angular forms in general, see the docs/tutorial

like image 136
Paul Samsotha Avatar answered Sep 28 '22 01:09

Paul Samsotha


Apart from using form controls directly as @peeskillet has shown in his answer, you can attach the form directive to any tag using its ngForm selector:

<div ngForm #newRuleForm="ngForm">   <div class="form-group">     <label for="name">Name</label>     <input type="text" class="form-control" id="name">   </div>   <button type="button" class="btn btn-default" [disabled]="!newRuleForm.valid" (click)="save()">Save</button> </div> 

Keep in mind that you can't use standard form functionality like <button type=submit> in this case, but I find this approach very valuable when I want to use template-driven forms while retaining a simple way to validate a group of fields together.

like image 45
Johannes Rudolph Avatar answered Sep 28 '22 01:09

Johannes Rudolph