coder
coder

Reputation: 849

Form group validation

i want to show message on submit as well , so please correct me how to validate on submit . here my html

    <input type="text" class="form-control" formControlName="code" required>
 <label [hidden]="ascForm.controls.code.valid || (ascForm.controls.code.pristine && ascForm.submitted)" class="errorMsg">Cannot save. You must specify a code.</label>

this validation condition is working fine if i use template driven approach, but now i am using Model driven so please correct me submit condition.

Upvotes: 0

Views: 326

Answers (1)

Petr Adam
Petr Adam

Reputation: 1437

Common approach is to disable the submit button, until the form is completely valid.

But if you want to show messages only when the user actually submits the form, lets create in your FormComponent boolean property indicating the user tried to post the form. Like:

submitAttempt: boolean = false;

and on submitting the form, in your component you set it to true:

submitForm() {
    this.submitAttempt = true;
    ...
  }

You can then filter your message just submitAttempt == true. Like:

<span *ngIf="!code.valid && submitAttempt">Required</span>

For deep explanation, see this post: Angular 2 forms validation, (search the page for 'submitAttempt' to quickly find the referenced part)

PS: please don't use label tag for showing validation errors. It should be used really just for labeling the form inputs.

Upvotes: 1

Related Questions