【问题标题】:Form Validation between multiple input fields多个输入字段之间的表单验证
【发布时间】:2018-04-29 19:55:00
【问题描述】:

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

 <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 类是给定的,但我无法让它成为可选的。

【问题讨论】:

    标签: javascript forms angular validation angular4-forms


    【解决方案1】:

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

    构建形式:

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

    【讨论】:

      【解决方案2】:

      请按以下步骤操作:

      注意:我们只是提供您如何解决问题的想法。

      1. 在 module.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'导入{组件}; 从 '@angular/forms' 导入 { FormBuilder, FormGroup, Validators };

        @组件({ 选择器:'应用程序登录', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) 导出类 LoginComponent {

        登录表单:FormGroup;

        构造函数(私人FB:FormBuilder){ this.crateLoginForm() }

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

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

        onSubmit() { 让用户名= this.loginForm.value.userName; 让 pwd =this.loginForm.value.password; }

        }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-14
        • 2017-11-09
        • 1970-01-01
        • 1970-01-01
        • 2019-03-06
        • 2011-04-17
        • 2013-10-11
        • 1970-01-01
        相关资源
        最近更新 更多