Validation message should display later when I don't give any input. But it is coming as soon as page loads.
CodePudding user response:
Add form.touched method to Validation messages which will display it only when you start to fill that field.
<label for="userName">UserName</label>
<input type="text" id="userName" name="userName"
[class.is-invalid]="form['userName'].invalid && form['userName'].touched" formControlName="userName"
placeholder="Enter Username">
<div *ngIf="form['userName'].touched && form['userName'].invalid" >
<small *ngIf="form['userName'].errors?.['required']">Username is Required</small>
</div>
CodePudding user response:
You can show the validation message when the form field touched and dirty property
Example form group
this.formGroup = this.formBuilder.group({
toDo: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(30)]]
});
Example HTML
<input
id="toDo"
type="text"
placeholder="What is it you want to do?"
formControlName="toDo"
[class.valid]="formGroup.get('toDo').valid &&
(formGroup.get('toDo').dirty || formGroup.get('toDo').touched)"
[class.invalid]="formGroup.get('toDo').invalid &&
(formGroup.get('toDo').dirty || formGroup.get('toDo').touched)" />
<div *ngIf="formGroup.get('toDo').invalid &&
formGroup.get('toDo').errors &&
(formGroup.get('toDo').dirty || formGroup.get('toDo').touched)">
<small
*ngIf="formGroup.get('toDo').hasError('required')">
This field is required.
</small>
<small
*ngIf="formGroup.get('toDo').hasError('minlength')">
The minimum length for this field is {{formGroup.get('toDo').errors.minlength.requiredLength}} characters.
</small>
<small
*ngIf="formGroup.get('toDo').hasError('maxlength')">
The maximum length for this field is {{formGroup.get('toDo').errors.maxlength.requiredLength}} characters.
</small>
</div>
dirty property will return true if the element’s contents have been changed.
touched property will return true if the user has visited the element.