Ilja
Ilja

Reputation: 46479

Apply error class and show related validation messages for incorrect fields after form submission? angular 2

My function for form submission looks like this at the moment:

submitListing(value: string): void {
    if(this.newListingForm.valid) {
      console.log("Form Valid");
    } else {
      console.log("Form Invalid");
    }
  }

Here I check if my whole form is valid, if not (else condition) I want to apply .error class to all invalid fields within this form and show related error messages. I was able to follow this guide on forms and understand how to achieve this while users enter data in the form, however how can I do this after form is submitted?

Here is example part from the form:

<form [ngFormModel]="newListingForm" (ngSubmit)="submitListing(newListingForm.value)">

<input type="text" placeholder="New Title" [(ngModel)]="mainTitleInput" [ngFormControl]="newListingForm.find('mainTitleInput')" id="main-title_input" class="transparent">

<!-- etc.. -->

</form>

and related validation code (using FormBuilder) in my app.ts

//New Listing Form
this.newListingForm = fb.group({
  'mainTitleInput': ['', Validators.compose([Validators.required])]
});

Upvotes: 3

Views: 342

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202138

To complete the Günter's answer, you could also leverage the ngClass directive to add some classes to display errors. For example with Twitter Bootstrap it would be the has-error class:

<form [ngFormModel]="companyForm">
  (...)
  <div class="form-group form-group-sm"
       [ngClass]="{'has-error':!companyForm.controls.name.valid}">
    <label for="for" class="col-sm-3 control-label">Name</label>

    <div class="col-sm-8">
      <input [ngFormControl]="companyForm.controls.name"
             [(ngModel)]="company.name"/>
      <span *ngIf="!companyForm.controls.name.valid"
            class="help-block text-danger">
        <span *ngIf="companyForm.controls.name?.errors?.required">
          The field is required
        </span>
      </span>
    </div>
  </div>

Hope it helps you, Thierry

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657078

Just set a field in your class and include it in your condition you use to show error indicators (*ngIf="!newListingForm.controls['mainTitleInput'].valid && isSubmitted).

var isSubmitted: boolean = false;

submitListing(value: string): void {
  this.isSubmitted = true;
  if(this.newListingForm.valid) {
    console.log("Form Valid");
  } else {
    console.log("Form Invalid");
  }
}

Upvotes: 1

Related Questions