The validators are the rule which validates the value of FormControl, it can be changed using FormControl and if it has any error occurs while validating value against the validators, it can be access using FormControl instance.
Form validation
Template driven form validation
The validation is important part in form. Its common that the users will make mistakes while filling the form. The validation module must ensure that the provided information must be accurate and complete in the form fields. It is important to display proper validation error messages to the users, or disable the submit button until form is not valid.
template driven form validation
1 <div>
2 <div *ngIf="!domain?.valid && (domain?.dirty || domain?.touched)">
3 Invalid domain
4 </div>
5 <label for="domain">Domain</label>
6 <input type="text" id="domain" name="domain" pattern="^[a-zA-Z]+$" [(ngModel)]="loginData.domain">
7 </div>
Reactive form validation
The validation is important part in form. Its common that the users will make mistakes while filling the form. The validation module must ensure that the provided information must be accurate and complete in the form fields. It is important to display proper validation error messages to the users, or disable the submit button until form is not valid.
1 import { Component } from "@angular/core";
2 import { FormControl, FormGroup, Validators } from "@angular/forms";
3
4 @Component({
5 selector: 'app-root',
6 templateUrl: './app.component.html'
7 })
8
9 export class AppComponent {
10
11 loginForm = new FormGroup({
12 domain: new FormControl('', [Validators.required]),
13 username: new FormControl('', [Validators.required]),
14 password: new FormControl('', [Validators.required]),
15 });
16
17 submit() {
18 console.log(this.loginForm.value);
19 }
20 }
Change validators dynamically
Angular allows to change validator dynamically if required. It provides methods to change the validators for the controls, by using setValidators() and setAsyncValidators() method and to remove the validators from the control by using clearValidators() and clearAsyncValidators() method.
Change validators dynamically
1 setValidator() {
2 this.loginForm.get("username").setValidators([Validators.required, Validators.minLength(5)]);
3 this.loginForm.get("username").updateValueAndValidity();
4 }
Errors in FormControl
Angular allows to deal with FormControl errors. It is possible to update the error, get the errors of FormControl and set the custom errors to the FormControls.
1 showErrors() {
2 const errors : ValidationErrors = this.loginForm.get("username").errors;
3 if (errors) {
4 Object.keys(errors).forEach( key => {
5 console.log(key);
6 });
7 }
8 }
Related options for your search