多个输入字段之间的表单验证

时间:2017-11-16 10:13:32

标签: javascript forms angular validation angular4-forms

所以我有一个包含多个输入表单字段和嵌套表单组的表单。在嵌套表单组中,验证应该是这样的:如果填充了三个输入中的任何一个,那么表单应该是有效的。这个人可以填写全部,甚至只填一个,表格应该有效。我的模板代码如下:

 <h3 class="form-title">{{title}}</h3>
<form [formGroup]="formX" novalidate>
    <div formGroupName="brandIdentifier">
        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="brandName.valid && brandName.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="brandName.invalid && brandName.touched">close</mat-icon>
            <input matInput type="text" placeholder="Brand Name" formControlName="brandName" />
        </mat-form-field>
        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="brandId.valid && brandId.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="brandId.invalid && brandId.touched">close</mat-icon>
            <input matInput type="text" placeholder="Brand Id" formControlName="brandId" />
        </mat-form-field>
        <mat-form-field class="full-width">
            <mat-icon matSuffix color="primary" *ngIf="contentId.valid && contentId.touched">done</mat-icon>
            <mat-icon matSuffix color="primary" *ngIf="contentId.invalid && contentId.touched">close</mat-icon>
            <input matInput type="text" placeholder="Content Id" formControlName="contentId" />
        </mat-form-field>
    </div>
    <mat-form-field class="full-width">
        <mat-icon matSuffix color="primary" *ngIf="startTime.valid && startTime.touched">done</mat-icon>
        <mat-icon matSuffix color="primary" *ngIf="startTime.invalid && startTime.touched">close</mat-icon>
        <input matInput type="text" placeholder="Start Time" formControlName="startTime" />
    </mat-form-field>
    <mat-form-field class="full-width">
        <mat-icon matSuffix color="primary" *ngIf="endTime.valid && endTime.touched">done</mat-icon>
        <mat-icon matSuffix color="primary" *ngIf="endTime.invalid && endTime.touched">close</mat-icon>
        <input matInput type="text" placeholder="End Time" formControlName="endTime" />
    </mat-form-field>

    <button mat-raised-button color="primary" (click)="startAnalysis()" [ngClass]="{'form-valid':formX.valid, 'form-invalid':formX.invalid}">Submit</button>

    <pre>{{formX.value | json}}</pre>
</form>

我该怎么做?使用Validator类是给定的,但我无法使其成为可选项。

2 个答案:

答案 0 :(得分:2)

您可以为此使用自定义验证器,为嵌套组应用自定义验证器,我们检查三个字段中至少有一个字段的值是否为空字符串,所以这是一个示例:

构建表单:

this.myForm = this.fb.group({
  nestedGroup: this.fb.group({
    first: [''],
    second: [''],
    third: ['']
    // apply custom validator for the nested group only
  }, {validator: this.myCustomValidator})
});

自定义验证器:

 myCustomValidator(group: FormGroup) {
   // if true, all fields are empty
   let bool = Object.keys(group.value).every(x => group.value[x] === '')
   if(bool) {
     // return validation error
     return { allEmpty: true}
   }
   // valid
   return null;
 }

然后在表单中,您可以通过以下方式显示验证消息:

<small *ngIf="myForm.hasError('allEmpty','nestedGroup')">
  Please fill at least one field
</small>

最后是 DEMO :)

答案 1 :(得分:0)

请按照以下步骤操作:

注意:我们只是想知道如何解决问题。

  1. 导入Forms.ts中的FormsModule,ReactiveFormsModule

    从'@ angular / forms'导入{FormsModule,ReactiveFormsModule};

    @NgModule({ 导入:[FormsModule,ReactiveFormsModule]})

  2. 修改您的html,例如

                                                                                 用户名                                                                                                                                                                                用户名是必需的。                                                                                                                                           用户名长度必须至少为4个字符。                                                                                                                                                                                                         密码                                                                                                                                                                                密码是必需的。                                                                                                                                           密码必须至少有6个字符长。                                                                                                                               忘记密码?                                     

                                    <div class="form-group">
                                        <button type="submit" (click)='onSubmit()' dir-btn-click  [disabled]="!loginForm.valid" class="btn btn-inverse btn-block">Sign in</button>
                                    </div>
    
                                </form>
    
  3. 修改[yourcomponent] .ts中的代码,例如:

    从'@ angular / core'导入{Component}; 从'@ angular / forms'导入{FormBuilder,FormGroup,Validators};

    @Component({   选择器:'app-login',   templateUrl:'。/ login.component.html',   styleUrls:['。/ login.component.css'] }) 导出类LoginComponent {

    loginForm:FormGroup;

    构造函数(private fb:FormBuilder){     this.crateLoginForm()   }

    get userName(){return this.loginForm.get('userName'); }   get password(){return this.loginForm.get('password'); }

    crateLoginForm(){     this.loginForm = this.fb.group({       userName:['',[Validators.required,Validators.minLength(4)]],       密码:['',[Validators.required,Validators.minLength(6)]]     })   }

    onSubmit(){     let userName = this.loginForm.value.userName;     let pwd = this.loginForm.value.password;   }

    }