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>
Yes, you can use FormControlDirective without FormGroup.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With