Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display only single validation error at a time

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?

like image 993
sreginogemoh Avatar asked Apr 06 '16 06:04

sreginogemoh


People also ask

How can I see all validation errors in one place?

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.

How do you create a validation error?

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.


1 Answers

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>
like image 107
Joe Avatar answered Oct 21 '22 13:10

Joe