Reputation: 982
Is there a way to change the validation message of FormBuilder in Angular? I have this code below that gives the 'red' word 'wrong' whenever the input field is left blank. The validator works but I just want to change it to something more meaningful like "This field is required".
<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" id="UserName" class="form-control" mdbInputDirective>
<label for="UserName">Your UserName</label>
<div *ngIf="subscriptionForm.get('UserName').hasError('required')">
This field is required!
</div>
</div>
<br>
<div class="md-form">
<i class="fa fa-user prefix grey-text"></i>
<input type="text" formControlName="FirstName" id="FirstName" class="form-control" mdbInputDirective>
<label for="FirstName">Your First name</label>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<button class="btn btn-indigo btn-lg btn-block waves-light" type="button" (click)="onSubmit()" [disabled]="!subscriptionForm.valid" mdbWavesEffect>Send
<i class="fa fa-paper-plane-o ml-1"></i>
</button>
</div>
</div>
</form>
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.subscriptionForm = this.fb.group({
UserName: [null, Validators.required],
FirstName: [null, Validators.required]
});
}
If you will notice I tried creating an *ngIf but somehow, it doesn't work. However, I would like it better if I do not have to create this *ngIf but if there is really no way to do it, then *ngIf is fine. Can you please help me with this? Thank you.
Upvotes: 3
Views: 6360
Reputation: 1583
Use this code
<div *ngIf="subscriptionForm.get('UserName').errors.required">
This field is required!
</div>
Upvotes: 1
Reputation: 12996
<app-form-group-control-validation-display [formGroup]="subscriptionForm" [propertyName]="'UserName'" [custom]="[{'required':'This field is required !'}]">
</app-form-group-control-validation-display>
Upvotes: 0