Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing an error message on form submit in angular2?

Tags:

angular

I have implemented model driven form in this demo. If the user doesn't enter anything and submits the form I am showing an error message using this logic

<div *ngIf="(!myForm.find('sku').valid && submitted)">**sku is required</div>

I am passing a boolean variable 'submitted' to check whether a control is valid or not when submitted. Is there any way to check the state of the control without passing a variable manually? Angular2 forms gives us 6 classes like ng-touched, ng-untouched, ng-valid, ng-invalid, ng-pristine, and ng-dirty. I want to show the error message using only these classes.

like image 759
abhilash reddy Avatar asked Feb 03 '16 05:02

abhilash reddy


People also ask

How do you validate a reactive form?

In a reactive form, the source of truth is the component class. Instead of adding validators through attributes in the template, you add validator functions directly to the form control model in the component class. Angular then calls these functions whenever the value of the control changes.


1 Answers

I know that question is posted a long time ago, but I got the same problem and I wanted to utilize angular control states, so found this working properly:

First I would show error only if control is not pristine:

<span class="help-block" 
      *ngIf="request.get('control').hasError('required') && 
            !request.get('control').pristine">
      This field is required!
</span>

Then you can go trough all controls and mark them as dirty in onSubmit function:

onSubmit() {
//validations
this.form.updateValueAndValidity();
if (this.form.invalid) {
  Object.keys(this.form.controls).forEach(key => {
    this.form.get(key).markAsDirty();
  });
  return;
}

//call function for saving data
this.save(this.form.value);
}

Hope this helps

like image 110
Bojan Avatar answered Sep 24 '22 02:09

Bojan