Bharath Sagar
Bharath Sagar

Reputation: 52

How to show form validation messages while using [(ngModel)] in Angular 2?

I am struggling for the validation error message.

I have a form and I have used ngModel. Now I am not able to display the error messages Depending on the Pattern. I have written validation in component.ts.

Could anyone help me with the two type of messages 1. Required 2. Validation message for form which is invalid with respect to the pattern (Validation using pattern).

I searched all places for the above with no help, it would be appreciated if anyone could help me with this.

Component.html

<div class="card card-blur">
  <div class="card-header">
    <p>ACCOUNT INFORMATION</p>
  </div>
  <div class="card-body">
    <div class="row">
      <div class="col-md-3">
        <!-- <p>Profile Image</p>
          <img src={{client.ProfileImage}} type="text" name="ProfilePic" style="width:60%"> -->
        <ba-picture-uploader [picture]="client.ProfileImage" [defaultPicture]="defaultPicture" [uploaderOptions]="uploaderOptions"></ba-picture-uploader>
      </div>
      <div class="col-md-9">
        <ul style="margin-top:20px;">
          <ul style="margin-top:20px;">
            <!-- <li>Take picture of id from your phone or mobile camera</li> -->
          </ul>
        </ul>

      </div>
    </div>
    <form #f="ngForm" (submit)="submit()">
      <fieldset>

        <div class="row form-inline">
          <div class="col-md-6">
            <div class="col-md-3"></div>
            <div class="col-md-9"></div>
          </div>
          <div class="col-md-6">
            <!-- <div class="form-group" style="margin-left: 16em; margin-top: -5em"> -->
            <div class="form-group" style=" margin-top: -3.5em">
              <div class="col-md-3">
                <label for="organization">Organization</label>
              </div>
              <div class="col-md-9">
                <input [(ngModel)]="client.Organization" type="text" name="Organization" class="form-control" id="organization"
                  placeholder="Organization">
              </div>
            </div>
          </div>
        </div>

        <div class="row form-inline">
          <div class="col-md-6">
            <div class="form-group">
              <div class="col-md-3">
                <label for="fname">First Name</label>
              </div>
              <div class="col-md-9">
                <input [(ngModel)]="client.ClientFirstName" type="text" name="FirstName" class="form-control" id="fname"
                  placeholder="First Name">
              </div>
            </div>
          </div>
          <div class="col-md-6">
            <div class="form-group">
              <div class="col-md-3">
                <label for="lname">Last Name</label>
              </div>
              <div class="col-md-9">
                <input [(ngModel)]="client.ClientLastName" type="text" name="lastN" class="form-control" id="lname"
                  placeholder="Last Name">
              </div>
            </div>
          </div>
        </div>
        <br />
        <div class="row form-inline">
          <div class="col-md-6">
            <div class="form-group">
              <div class="col-md-3">
                <label for="email">Email </label>
              </div>
              <div class="col-md-9">
                <input [(ngModel)]="client.ContactEmailID" name="Email" type="email" class="form-control" id="email"
                  placeholder="Enter email">
              </div>
            </div>
          </div>
          <div class="col-md-6">
            <div class="form-group">
              <div class="col-md-3">
                <label for="pnumber">Phone Number</label>
              </div>
              <div class="col-md-9">
                <input [(ngModel)]="client.ContactMobileNo" name="PhoneNumber" type="text" class="form-control"
                  (keypress)="onlyNumberKey($event)" id="pnumber" placeholder="Phone Number" minlength="10" maxlength="10">
              </div>
            </div>
          </div>
        </div>
        <br />
      </fieldset>
      <button type="submit" class="btn btn-primary btn-sm" style="width:5em">Update</button>
    </form>

  </div>
  <!-- {{f.value | json}} -->
</div>

Component.ts where i have imported validators

this.form = fb.group({
  FirstName: [ "", Validators.compose([Validators.pattern(alphabetRegex), Validators.required])],
  LastName: ["", ([Validators.pattern(alphabetRegex), Validators.required])],
  Email: ["", Validators.compose([Validators.pattern(regexEmail), Validators.required])],
  PhoneNumber: ["", Validators.compose([Validators.required])],
});

Upvotes: 2

Views: 5242

Answers (5)

alokstar
alokstar

Reputation: 499

If you would like to see the simple template driven form validation working model with angular, you can take a look at the following: https://github.com/alokstar/Angular4FormValidation

It shows the simple error messages on the fly using data-binding in angular. Hope it helps!

Upvotes: 0

Khalid
Khalid

Reputation: 161

There are two types of forms in Angular, Template Driven and Reactive forms. It seems you are mixing them. [(ngModel)] belongs to template driven forms, while FormBuilder belongs to reactive forms. To learn about validation in both types, see https://angular.io/guide/form-validation

If you want to use reactive forms, learn more here https://angular.io/guide/reactive-forms

I recommend you pick one and stick with it in given project.

If validation is critical to you, reactive forms are probably the better choice because they provide powerful and flexible validation.

Upvotes: 2

Likhith Kolayari
Likhith Kolayari

Reputation: 154

Before answering your question, I would like to make a suggestion. In your code, you have mixed the concepts of Reactive/Model driven forms(Component.ts) and template driven forms (Component.html).

  1. If you wish to follow template driven form, please use:

    <input type="text" id="fName" class="form-control" required pattern="[A-Z]{5}" [(ngModel)]="FirstName" name="FirstName" #fName="ngModel" />

    <div [hidden]="!fName.errors.required">FirstNameis required!</div>

    <div [hidden]="!fName.errors.pattern">FirstName must be at least 5 characters long</div>

In this case you need not have the form builder object in .ts file.

  1. If you are using reactive forms

    <input type="text" class="form-control" formControlName="FirstName" id="FirstName" placeholder="Enter First Name"/>

    <div *ngIf="form.controls.FirstName.errors.required">Field is required.</div>

    <div *ngIf="form.controls.FirstName.errors.pattern">Can contain only alphabets and at least three characters required</div>

Upvotes: 2

Sudarshana Dayananda
Sudarshana Dayananda

Reputation: 5265

Use FormControl and Validators from @angular/forms for form field validations as below.

this.form = new FormGroup({
      FirstName : new FormControl( '', [ Validators.required, Validators.pattern(alphabetRegex) ]),
      LastName : new FormControl( '', [ Validators.required, Validators.pattern(alphabetRegex) ]),
      Email : new FormControl( '', [ Validators.required, Validators.pattern(regexEmail) ]),
      PhoneNumber : new FormControl( '', [ Validators.required ]),
  });

Remember to add import FormControl, FormGroup and Validator in your component as below.

import { FormControl, FormGroup, Validators } from '@angular/forms';

You can show validation in HTML as below.

<form #f="ngForm" (submit)="submit()" [formGroup]="myform">       
    <div class="row form-inline">
        <div class="col-md-6">
            <div class="form-group">

                  <div class="col-md-3">
                    <label for="fname">First Name</label>
                  </div>

                  <div class="col-md-9">
                    <input [(ngModel)]="client.ClientFirstName" type="text" name="FirstName" class="form-control" id="fname"
                      placeholder="First Name">
                  </div>

                  <div>
                      <span *ngIf="(
                      myform.get('FirstName').hasError('required') &&
                      myform.get('FirstName').touched)">Please enter first name</span>

                      <span class="error-message" *ngIf="(
                      myform.get('FirstName').hasError('pattern') &&
                      myform.get('FirstName').touched)">Enter valid first name </span>
                  </div>

            </div>
         </div>
    </div>
</form>

Hope this will help you.

Upvotes: 1

Sunil
Sunil

Reputation: 11241

Add [formGroup] in <form> element and formControlName to form element.

Look at this sample demo - https://stackblitz.com/edit/angular-yeyiuk

Upvotes: 0

Related Questions