简体   繁体   English

在Angular 2中使用[[ngModel)]时如何显示表单验证消息?

[英]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 . 我有一个表格,并且使用了ngModel Now I am not able to display the error messages Depending on the Pattern. 现在,根据模式,我将无法显示错误消息。 I have written validation in component.ts. 我已经在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). 有人可以帮助我处理两种类型的消息吗?1.必需2.形式验证消息,该消息对模式无效(使用模式进行验证)。

I searched all places for the above with no help, it would be appreciated if anyone could help me with this. 我在没有帮助的情况下在所有地方搜索了上述内容,如果有人可以帮助我,将不胜感激。

Component.html 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 我已导入验证器的Component.ts

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])],
});

Use FormControl and Validators from @angular/forms for form field validations as below. 使用@angular/forms FormControlValidators进行表单字段验证,如下所示。

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 FormControlFormGroupValidator

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

You can show validation in HTML as below. 您可以按以下所示以HTML显示验证。

<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. 希望这会帮助你。

There are two types of forms in Angular, Template Driven and Reactive forms. Angular中有两种类型的表单:“模板驱动”表单和“反应式”表单。 It seems you are mixing them. 看来您正在混合它们。 [(ngModel)] belongs to template driven forms, while FormBuilder belongs to reactive forms. [(ngModel)]属于模板驱动形式,而FormBuilder属于反应形式。 To learn about validation in both types, see https://angular.io/guide/form-validation 要了解两种类型的验证,请参阅https://angular.io/guide/form-validation

If you want to use reactive forms, learn more here https://angular.io/guide/reactive-forms 如果要使用反应形式,请在此处了解更多信息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. 如果验证对您至关重要,则反应形式可能是更好的选择,因为它们提供了强大而灵活的验证。

Add [formGroup] in <form> element and formControlName to form element. <form>元素和formControlName添加[formGroup]到form元素。

Look at this sample demo - https://stackblitz.com/edit/angular-yeyiuk 看看这个示例演示-https: //stackblitz.com/edit/angular-yeyiuk

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). 在您的代码中,您混合了Reactive / Model驱动的表单(Component.ts)和模板驱动的表单(Component.html)的概念。

  1. If you wish to follow template driven form, please use: 如果您希望遵循模板驱动的形式,请使用:

    <input type="text" id="fName" class="form-control" required pattern="[AZ]{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. 在这种情况下,您无需在.ts文件中包含表单生成器对象。

  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>

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 如果您想查看带有angular的简单模板驱动的表单验证工作模型,可以查看以下内容: https : //github.com/alokstar/Angular4FormValidation

It shows the simple error messages on the fly using data-binding in angular. 它使用角度数据绑定实时显示简单的错误消息。 Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM