I have this code to which displaying errors on my form
<input [ngFormControl]="form1.controls['thing']" type="text" id="thing" #thing="ngForm">
<div *ngIf='thing.dirty && !thing.valid'>
<div class="err" *ngIf='thing.errors.required'>
Thing is required.
</div >
<div class="err" *ngIf='thing.errors.invalid'>
Thing is invalid.
</div >
</div>
But in case of thing
has two errors in it the two error show up.
Lets say if my input has 5 validators
so 5 divs
will show up which is not nice.
How to display just one error div
at a time?
To display summarized error messagesAdd a ValidationSummary control to the page at the location where you want to display the collected error messages. Set the ErrorMessage and Display properties of the individual validation controls. (Default) Each error message appears as a bulleted item.
Add Data Validation by Using the User Interface Click to select the Age text box control. On the Home tab, click Add Rule, click Is Not Between, and then click Show Validation Error. In the ScreenTip text box of the Rules pane, type The value of the Age field must be greater than 30 and less than 65.
If you have consistent markup for your error message blocks, then you can use css to display only the first message and hide the rest:
css
.message-block .error-message {
// Hidden by default
display: none;
}
.message-block .error-message:first-child {
display: block;
}
markup
<div class="message-block">
<span class="error-message" *ngIf="myForm.get('email').hasError('required')">
Email is required (first-child of message block is displayed)
</span>
<span class="error-message" *ngIf="myForm.get('email').hasError('email')">
Invalid email format (error message hidden by default)
</span>
</div>
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