Validating a form between multiple input fields

So, I have a form with several input form fields and a group of nested forms. In the nested form group, the check must be such that if any of the three inputs is filled in, the form must be valid. A person can fill in either all or even one, and the form must be valid. My template code is as follows:

 <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>

How can i do this? using the Validator class is data, but I cannot get it optional.

+4
source share
2 answers

, , , , , :

:

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>

a DEMO:)

+2

, :

: , .

  • FormsModule, ReactiveFormsModule module.ts

    import {FormsModule, ReactiveFormsModule} '@ angular/forms';

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

  • 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>
    
  • , [yourcomponent].ts, :

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

    @Component ({ : 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) LoginComponent {

    loginForm: FormGroup;

    (private fb: FormBuilder) {   this.crateLoginForm() }

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

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

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

    }

0

Source: https://habr.com/ru/post/1689369/


All Articles