Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular reactive form validator is showing error message initially?

I have one reactive form validator sample. it shows validation error message initially before we enter value.

expected behavior is, after enter value it has to show error message

sample link

like image 761
Kumaresan Sd Avatar asked Oct 29 '25 17:10

Kumaresan Sd


2 Answers

You have to check touched for your error message like this

 <div *ngIf="check.errors.required && check.touched" class="e-error">
                This field is required.
 </div>

You are checking required so simply when you load the form then your field is obviously empty so it will throw the error.

You will get more information and example here : Built In Validators and Reactive Form Validattions

like image 70
Aarsh Avatar answered Oct 31 '25 07:10

Aarsh


Create a Form Service and Use Mark FormGroup Touched so that it will defaultly don't display the Error Messages

import { FormService } from './services/form';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.scss' ]
})

export class AppComponent  {
 public testForm: FormGroup;

ngOnInIt(){
 this.testForm.valueChanges.subscribe((data) => {
    this.FormService.markFormGroupTouched(this.testForm);
})
}
}
like image 20
balajivaishnav Avatar answered Oct 31 '25 06:10

balajivaishnav