在angular2中进行表单生成器验证

时间:2017-11-06 05:19:37

标签: angular angular2-forms angular-reactive-forms

我的问题是,当用户单击提交按钮而不填写必填字段时,它必须显示错误。我搜索了很多我没有找到解决方案是新的角度所以任何人都帮我解决问题。

<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)" class="wpcf7-form">
  <p></p>
  <div formGroupName="serviceProviderDetail">
    <input formControlName="mobileStatus" placeholder="Please enter your name" type="hidden">
    <div formGroupName="user">
      <h6>First Name</h6>
      <p><span class="wpcf7-form-control-wrap your-name">
         <input formControlName="firstName" placeholder="Please enter your name" type="text"   name="firstName" id="firstName" [formControl]="firstName" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required"  >
          <div*ngIf="myForm.controls.serviceProviderDetail.controls.user.controls['firstName'].dirty && myForm.controls.serviceProviderDetail.controls.user.controls['firstName'].invalid   "class="alert alert-danger">
        Please enter a firstName
  </div>  
  </span>
      </p>
    </div>
    <button type="submit"  class="btn btn-warning" style="background-color:#FF812D;font-size:18px;width:200px;text-align: center;margin-left: 37%;margin-bottom: 5%;">Submit</button>
  </div>
</form>

4 个答案:

答案 0 :(得分:1)

使用输入标记中的必需条件进行更详细的验证 enter image description here

&#13;
&#13;
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)" class="wpcf7-form">
  <p></p>
  <div formGroupName="serviceProviderDetail">
    <input formControlName="mobileStatus" placeholder="Please enter your name" type="hidden">
    <div formGroupName="user">
      <h6>First Name</h6>
      <p><span class="wpcf7-form-control-wrap your-name">
         <input required formControlName="firstName" placeholder="Please enter your name" type="text"   name="firstName" id="firstName" [formControl]="firstName" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required"  >
          <div*ngIf="myForm.controls.serviceProviderDetail.controls.user.controls['firstName'].dirty && myForm.controls.serviceProviderDetail.controls.user.controls['firstName'].invalid   "class="alert alert-danger">
        Please enter a firstName
  </div>  
  </span>
      </p>
    </div>
    <button type="submit" [disabled]="myForm.valid" class="btn btn-warning" style="background-color:#FF812D;font-size:18px;width:200px;text-align: center;margin-left: 37%;margin-bottom: 5%;">Submit</button>
  </div>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在输入字段中使用required =“true”

<input formControlName="firstName" placeholder="Please enter your name" type="text"   name="firstName" id="firstName" [formControl]="firstName" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" required="true" >

答案 2 :(得分:0)

存在语法问题,并且没有为被动表单提供代码,因此我将示例缩减为firstName及其错误消息。通过formControlName语法猜测,我假设您正在使用reactive forms,但如果您尝试使用模板表单(例如ngModel),请告诉我。

  1. 根据需要标记控件:使用firstName构建Validators.required表单控件:firstName: ['', Validators.required]
  2. 在表单无效时禁用提交:当表单无效时,应禁用“提交”按钮,而不是在表单有效时:<button [disabled]="myForm.invalid">Submit</button>
  3. 我注意到,当用户点击带有空字符串的提交按钮时,系统会要求您显示该消息。相反,这种方法在表单无效时禁用按钮,就像用户没有给出名字一样。如果用户开始提供名字并将其删除,则会显示错误消息,提醒用户该字段是必需的(看起来您已经有了该字段),该按钮将再次禁用。

    form.component.html:

    <form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm.value)">
      <div formGroupName="serviceProviderDetail">
        <h6>First Name</h6>
        <input formControlName="firstName" placeholder="Please enter your name" type="text" name="firstName" id="firstName">
        <div *ngIf="firstNameControl && firstNameControl.dirty && firstNameControl.invalid" class="alert alert-danger">
          First name is required
        </div>
        <button type="submit" [disabled]="myForm.invalid">Submit</button>
      </div>
    </form>
    

    form.component.ts

    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html'
    })
    export class AppComponent {
    
      myForm: FormGroup;
    
      get firstNameControl() {
        return this.myForm.controls['serviceProviderDetail'].controls['firstName'];
      }
    
      constructor(_fb: FormBuilder) {
        this.myForm = _fb.group({
          serviceProviderDetail: _fb.group({
            firstName: ['', Validators.required]
          })
        });
      }
    
      onSubmit(value) {
        console.log('Submit value:', value);
      }
    
    }
    

    希望这会有所帮助。这是一个plunker来继续修修补补,如果错过了你的要求,请告诉我。

答案 3 :(得分:-1)

我对我的离子项目采用了相同的表格控件。 PFB注册页面。忽略离子标签,其他一切都是一样的,你也可以了解你的Angular 2项目。在下面的typescript文件中声明表单和控件变量

public signUpForm:FormGroup;
    public name:FormControl;
    public email:FormControl;
    public userId:FormControl;
    public faculty:FormControl;
    public terms:FormControl;

PFB HTML文件

<form [formGroup]="signUpForm" (submit)="register()">
            <ion-card>
                <ion-list class="login-data">
                    <ion-item [class.error]="!name.valid && name.touched">
                        <ion-input type="text" placeholder="Name" [(ngModel)]="registration.name" formControlName="name"></ion-input>
                    </ion-item>


                    <ion-item [class.error]="!email.valid && email.touched">
                        <ion-input  type="text" (blur)="triggerUserId()"  [(ngModel)]="registration.emailId" placeholder="Email"  formControlName="email"></ion-input>
                    </ion-item>

                    <ion-item [class.error]="!userId.valid && userId.touched">
                        <ion-input type="text" placeholder="Username"  [(ngModel)]="registration.userId" formControlName="userId"></ion-input>
                    </ion-item>

                    <!--<ion-item [class.error]="!faculty.valid && faculty.touched">
                        <ion-input type="text" placeholder="Faculty" [(ngModel)]="registration.facultyCode" formControlName="faculty"></ion-input>
                    </ion-item>-->

                    <ion-item>
                        <ion-label>Agreed <span color="primary">Terms & Condition</span></ion-label>
                        <ion-checkbox formControlName="terms"></ion-checkbox>
                    </ion-item>

                </ion-list>

            </ion-card>


            <div *ngIf="name.hasError('required') && name.touched"
                 class="error-box">* {{nameMissing}}
            </div>
            <!--<div *ngIf="!(name.hasError('required')) && name.hasError('pattern') && name.touched"
                 class="error-box">* Name should contain only characters.
            </div>-->
            <div *ngIf="!(name.hasError('required')) && !name.hasError('pattern') && email.hasError('required') && email.touched"
                 class="error-box">* {{emailMissing}}
            </div>
            <div *ngIf="!(name.hasError('required')) && !name.hasError('pattern') && !(email.hasError('required')) && email.hasError('pattern') && email.touched"
                 class="error-box">* {{emailNotValid}}
            </div>
            <div *ngIf="!(name.hasError('required')) && !name.hasError('pattern') && !(email.hasError('required')) && !email.hasError('pattern') &&  userId.hasError('required') && userId.touched"
                 class="error-box">* {{userNameMissing}}
            </div>
            <div *ngIf="!(name.hasError('required')) && !name.hasError('pattern') && !(email.hasError('required')) && !email.hasError('pattern') &&  !userId.hasError('required') && faculty.hasError('required') && faculty.touched"
                 class="error-box">* Please enter faculty code.
            </div>
            <!--<div *ngIf="!(name.hasError('required')) && !name.hasError('pattern') && !(email.hasError('required')) && !(email.hasError('pattern')) &&  !(userId.hasError('required')) && !(faculty.hasError('required')) && !(faculty.hasError('required'))&& !(terms.hasError('required'))&& terms.touched"-->
            <div *ngIf="!(name.hasError('required')) && !name.hasError('pattern') && !(email.hasError('required')) && !(email.hasError('pattern')) &&  !(userId.hasError('required')) && !(terms.hasError('required'))&& terms.touched"

                 class="error-box">* {{termsCondMissing}}
            </div>
            <ion-grid>
                <ion-row>
                    <ion-col>
                        <button ion-button block type="button" (click)="back()">Back</button>
                    </ion-col>
                    <ion-col>
                        <button ion-button block type="submit" (click)="userRegistration()"  [disabled]="!signUpForm.valid">Register</button>
                    </ion-col>
                </ion-row>
            </ion-grid>
        </form>