In Angular we can add specific rules to a form input field, such as required, minlength etc and then apply visual change in and user friendly feedback.
In template driven form all the these done in component template. We already learn how to capture data in a angular form, if you miss the post here is the link.
- How to capture data in Angular form using Model - How to capture data from a Angular form using Model and ngModel
- How to capture data in Angular form using `ngModel` and `FormsModule` ? - How to capture data from a Angular form using ngModel
Setting the rule
This is the simple step you just specify the rule in <input> tag.
<input type="text" #item="ngModel" required name="item" class="form-control" [(ngModel)]="todoModel.item">
This will tell the template this field is a compulsory field. If the user leave it blank it will return invalid props as true.
We can bind class according to validation status.
[class.is-invalid]="item.invalid && item.touched"
This will add red boarder for the input field , if the user leave it blank and user clicked the item and then tap outside the box.
A good app come with user friendly feed back, we conditionally place a small using the validation rules. The d-none class help us to hide the component when the input is valid
<small class="alert-danger" [class.d-none]="item.valid">title is required</small >
That is all about validation. Following angular form post may help you
- How to disable submit button in Angular forms based on validation - How to disable submit button on validation fail in Angular forms
- How to add validation rule to Angular Reactive form using form Builder - How to add validation rules to angular reactive form using form-Builder
- How to validate Angular Reactive form - How to validate angular reactive form and add some style using css class
- How to validate Angular form - How to validate angular form and add some style using css class
- How to create a Angular reactive from with formGroup - How to create angular reactive form with formgroup