Hi
I am usng Reactive Form . I want to sho Valodation messages on change of field
C#
form = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(3)]),
email: new FormControl('', [Validators.required, Validators.email])
)
});Thanks

Jayraj ChhayaRank #304 · 8.2K reputationPosted May 14, 2024, 2:31 AM EDT
To display validation messages on field change in Angular Reactive Forms, you can leverage the
valueChangesobservable provided by the form control.// Assuming 'form' is your FormGroup Object.keys(this.form.controls).forEach(key => { const control = this.form.get(key); if (control) { control.valueChanges.subscribe(() => { if (control.invalid && (control.dirty || control.touched)) { const errors = control.errors; // Handle errors and display appropriate messages } }); } });By subscribing to the
valueChangesobservable of each form control, you can listen for changes and trigger validation messages based on the control's state. Customize the error handling logic within the subscription to display validation messages as needed.Naimish MakwanaRank #324 · 7.7K reputationPosted May 14, 2024, 3:04 AM EDT
Sure, I can help with that. You can use Angular’s form control properties like
dirty,touched, andinvalidto show validation messages when the field changes. Here’s how you can do it:In this code, the
*ngIfdirective is used to conditionally show error messages when the form control isdirty(changed) andinvalid(fails validation). The specific error message is determined by the error type (required,minlength,email, etc.).Thanks
Jignesh KumarRank #91 · 22.9K reputationPosted May 14, 2024, 5:33 AM EDT
Hello Ramco,
You can use like the below in reactive form,
TypeScript: Component
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-user-form', templateUrl: './user-form.component.html', styleUrls: ['./user-form.component.css'] }) export class UserFormComponent implements OnInit { userForm: FormGroup; constructor(private fb: FormBuilder) { this.userForm = this.fb.group({ name: ['', Validators.required], email: ['', [Validators.required, Validators.email]], password: ['', [Validators.required, Validators.minLength(6)]] }); } ngOnInit(): void { } get f() { return this.userForm.controls; } }.cshtml
Name: Name is required. Email: Email is required. Invalid email address. Password: Password is required. Password must be at least 6 characters long. Submit