ngOnInit() { // Create a form with two fields, one for the name and one for the email address. const form = this.fb.group({ name: ['', [Validators.required]], email: ['', [Validators.required, Validators.email]] });
// Subscribe to the form's validity change event. form.valueChanges.subscribe((value) => { // Check if the form is valid. if (form.valid) { // The form is valid, do something. } else { // The form is invalid, display errors. } }); }
ngOnInit() { // Create a form with one field for a password. const form = this.fb.group({ password: ['', [Validators.required, this.passwordValidator]] });
// Subscribe to the form's validity change event. form.valueChanges.subscribe((value) => { // Check if the form is valid. if (form.valid) { // The form is valid, do something. } else { // The form is invalid, display errors. } }); }
// A custom validator that checks if the password is at least 8 characters long. passwordValidator(control: FormControl) { // Check if the password is at least 8 characters long. if (control.value.length < 8) { // The password is not valid, return an error message. return { message: 'The password must be at least 8 characters long.' }; }
// The password is valid, return null. returnnull; }