如何仅对angular 2+中的特定字段应用动态字段验证

时间:2018-09-27 04:46:18

标签: angular typescript

在这里,我尝试实现动态表单验证,即仅针对特定字段,因为我可以实现动态验证,但我想仅对我提到的那些字段实现5个字段。

说我有一个字段名称,例如名字,姓氏,年龄,性别,我也有一个数组,例如名字,性别,现在我想要的是并非所有字段都必须经过验证,我该如何实现

下面是我的示例代码

**.html**

<div class="jumbotron">
    <div class="container">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <h2>Angular 6 Reactive Form Validation</h2>
                <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
                    <div class="form-group">
                        <label>First Name</label>
                        <input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }" />
                        <div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
                            <div *ngIf="f.firstName.errors.required">First Name is required</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Last Name</label>
                        <input type="text" formControlName="lastName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.lastName.errors }" />
                        <div *ngIf="submitted && f.lastName.errors" class="invalid-feedback">
                            <div *ngIf="f.lastName.errors.required">Last Name is required</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
                        <div *ngIf="submitted && f.email.errors" class="invalid-feedback">
                            <div *ngIf="f.email.errors.required">Email is required</div>
                            <div *ngIf="f.email.errors.email">Email must be a valid email address</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Password</label>
                        <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
                        <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
                            <div *ngIf="f.password.errors.required">Password is required</div>
                            <div *ngIf="f.password.errors.minlength">Password must be at least 6 characters</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <button [disabled]="loading" class="btn btn-primary">Register</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {

   registerForm: FormGroup;
    submitted = false;

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
        this.registerForm = this.formBuilder.group({
            firstName: ['', Validators.required],
            lastName: ['', Validators.required],
            email: ['', [Validators.required, Validators.email]],
            password: ['', [Validators.required, Validators.minLength(6)]]
        });
    }

    // convenience getter for easy access to form fields
    get f() { return this.registerForm.controls; }

    onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.registerForm.invalid) {
            return;
        }

        alert('SUCCESS!! :-)')
    }
}

我的工作Stackblitz网址

https://stackblitz.com/edit/angular-mbagcm

2 个答案:

答案 0 :(得分:2)

this.formBuilder.group({ ABC: new FormArray([]), 

现在。

const abcFormArray = this.formBuilder.controls['ABC'] as FormArray;

Items = [Firstname, Lastname]

Items.forEach(() => {
// do your condition :-
abcFormArray.push((new FormControl(''))
}

答案 1 :(得分:1)

您可以根据以下条件为字段设置验证器

requiredValids: string[] = ['firstName', 'gender'];

this.registerForm = this.formBuilder.group({
  firstName: ['', this.requiredValids.indexOf('firstName') != -1 ? [Validators.required] : []],
  lastName: ['', this.requiredValids.indexOf('lastName') != -1 ? [Validators.required] : []],
  email: ['', this.requiredValids.indexOf('email') != -1 ? [Validators.required, Validators.email] : []],
  password: ['', this.requiredValids.indexOf('password') != -1 ? [Validators.required, Validators.minLength(6)] : []]
});

工作Stackblitz