I have this form that implements FormBuilder.
I need to show my custom validation message under the input field. With my code below, the validator can make a red "wrong" text appear whenever the input field is blank but it doesn't show my custom validation.
Please see code below for .html and .ts
<form [formGroup]="subscriptionForm">
<h3 style="color: gray; text-align: center;">Registration</h3>
<div class="row">
<div class="col-md-6">
<div class="md-form">
<i class="fa fa-user prefix grey-text"></i>
<input type="text" formControlName="UserName" name='UserName' id="UserName" class="form-control" mdbInputDirective>
<label for="UserName">Your UserName</label>
<div *ngIf="UserName?.invalid && (UserName?.dirty || UserName?.touched)" class="alert alert-danger">
<div *ngIf="UserName?.errors.required">
Username is required.
</div>
</div>
</div>
</div>
</div>
</form>
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.subscriptionForm = this.fb.group({
UserName: [null, Validators.required],
});
}
I have gone through the Angular - Form validation docs, that's where I got my codes, but I can't get it right. Thank you.
Try to change
*ngIf="UserName?.invalid && (UserName?.dirty || UserName?.touched)"
To
*ngIf="subscriptionForm.get('UserName').hasError('required') && subscriptionForm.get('UserName').touched"
In the view:
<div *ngIf="subscriptionForm.get('UserName').hasError('required') && subscriptionForm.get('UserName').touched" class="alert alert-danger">
Username is required.
</div>
Please try this Demo:
https://stackblitz.com/edit/angular-5xtbxm?file=app/app.component.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With